Удаление определенных файлов python

How can I delete a file or folder in Python?

Path objects from the Python 3.4+ pathlib module also expose these instance methods:

If the file doesn’t exist, os.remove() throws an exception, so it may be necessary to check os.path.isfile() first, or wrap in a try .

just for completion. the exception thrown by os.remove() if a file doesn’t exist is FileNotFoundError .

Does os.remove() take multiple arguments to delete multiple files, or do you call it each time for each file?

Python syntax to delete a file

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/.txt") file_to_rem.unlink() 

Unlink method used to remove the file or the symbolik link.

  • If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
  • If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
  • Changed in version 3.8: The missing_ok parameter was added.
Читайте также:  Python redis что это

Best practice

First, check if the file or folder exists and then delete it. You can achieve this in two ways:

EXAMPLE for os.path.isfile

#!/usr/bin/python import os myfile = "/tmp/foo.txt" # If file exists, delete it. if os.path.isfile(myfile): os.remove(myfile) else: # If it fails, inform the user. print("Error: %s file not found" % myfile) 

Exception Handling

#!/usr/bin/python import os # Get input. myfile = raw_input("Enter file name to delete: ") # Try to delete the file. try: os.remove(myfile) except OSError as e: # If it fails, inform the user. print("Error: %s - %s." % (e.filename, e.strerror)) 

Respective output

Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt

Python syntax to delete a folder

#!/usr/bin/python import os import sys import shutil # Get directory name mydir = raw_input("Enter directory name: ") # Try to remove the tree; if it fails, throw an error using try. except. try: shutil.rmtree(mydir) except OSError as e: print("Error: %s - %s." % (e.filename, e.strerror)) 

Exception handling is recommended over checking because the file could be removed or changed between the two lines (TOCTOU: en.wikipedia.org/wiki/Time_of_check_to_time_of_use) See Python FAQ docs.python.org/3/glossary.html#term-eafp

shutil.rmtree(path[, ignore_errors[, onerror]]) 

(See complete documentation on shutil) and/or

(Complete documentation on os.)

Here is a robust function that uses both os.remove and shutil.rmtree :

def remove(path): """ param could either be relative or absolute. """ if os.path.isfile(path) or os.path.islink(path): os.remove(path) # remove the file elif os.path.isdir(path): shutil.rmtree(path) # remove dir and all contains else: raise ValueError("file <> is not a file or dir.".format(path)) 

You can use the built-in pathlib module (requires Python 3.4+, but there are backports for older versions on PyPI: pathlib , pathlib2 ).

To remove a file there is the unlink method:

import pathlib path = pathlib.Path(name_of_file) path.unlink() 

Or the rmdir method to remove an empty folder:

import pathlib path = pathlib.Path(name_of_folder) path.rmdir() 

@Pranasas Unfortunately it seems there is nothing (natively) in pathlib that can handle deleting non-empty directories. However you could use shutil.rmtree . It has been mentioned in several of the other answers so I haven’t included it.

Deleting a file or folder in Python

There are multiple ways to Delete a File in Python but the best ways are the following:

  1. os.remove() removes a file.
  2. os.unlink() removes a file. it is a Unix name of remove() method.
  3. shutil.rmtree() deletes a directory and all its contents.
  4. pathlib.Path.unlink() deletes a single file The pathlib module is available in Python 3.4 and above.

os.remove()

Example 1: Basic Example to Remove a File Using os.remove() Method.

import os os.remove("test_file.txt") print("File removed successfully") 

Example 2: Checking if File Exists using os.path.isfile and Deleting it With os.remove

import os #checking if file exist or not if(os.path.isfile("test.txt")): #os.remove() function to remove the file os.remove("test.txt") #Printing the confirmation message of deletion print("File Deleted successfully") else: print("File does not exist") #Showing the message instead of throwig an error 

Example 3: Python Program to Delete all files with a specific extension

import os from os import listdir my_path = 'C:\\Python Pool\\Test' for file_name in listdir(my_path): if file_name.endswith('.txt'): os.remove(my_path + file_name) 

Example 4: Python Program to Delete All Files Inside a Folder

To delete all files inside a particular directory, you simply have to use the * symbol as the pattern string. #Importing os and glob modules import os, glob #Loop Through the folder projects all files and deleting them one by one for file in glob.glob(«pythonpool/*»): os.remove(file) print(«Deleted » + str(file))

os.unlink() is an alias or another name of os.remove() . As in the Unix OS remove is also known as unlink. Note: All the functionalities and syntax is the same of os.unlink() and os.remove(). Both of them are used to delete the Python file path. Both are methods in the os module in Python’s standard libraries which performs the deletion function.

shutil.rmtree()

Example 1: Python Program to Delete a File Using shutil.rmtree()

import shutil import os # location location = "E:/Projects/PythonPool/" # directory dir = "Test" # path path = os.path.join(location, dir) # removing directory shutil.rmtree(path) 

Example 2: Python Program to Delete a File Using shutil.rmtree()

import shutil import os location = "E:/Projects/PythonPool/" dir = "Test" path = os.path.join(location, dir) shutil.rmtree(path) 

pathlib.Path.rmdir() to remove Empty Directory

Pathlib module provides different ways to interact with your files. Rmdir is one of the path functions which allows you to delete an empty folder. Firstly, you need to select the Path() for the directory, and then calling rmdir() method will check the folder size. If it’s empty, it’ll delete it.

This is a good way to deleting empty folders without any fear of losing actual data.

from pathlib import Path q = Path('foldername') q.rmdir() 

Источник

Delete multiple files matching a pattern

I have made an online gallery using Python and Django. I’ve just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand. When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them per image (I have different ones for different occasions). I could hard-code in the file-varients. But that’s messy and if I change the way I do things, I’ll need to revisit the code. Ideally I’d like to do a regex-delete. In regex terms, all my originals are named like so:

9 Answers 9

import glob, os for f in glob.glob("P*.jpg"): os.remove(f) 

Alternatively, using pathlib:

from pathlib import Path for p in Path(".").glob("P*.jpg"): p.unlink() 

@sparrow The question was how to delete files matching a pattern, not to delete whole directory trees matching a pattern.

import os, re def purge(dir, pattern): for f in os.listdir(dir): if re.search(pattern, f): os.remove(os.path.join(dir, f)) 

Then you would pass the directory containing the files and the pattern you wish to match.

If you need recursion into several subdirectories, you can use this method:

import os, re, os.path pattern = "^(?P\d+)[^\d].*jpg$" mypath = "Photos" for root, dirs, files in os.walk(mypath): for file in filter(lambda x: re.match(pattern, x), files): os.remove(os.path.join(root, file)) 

You can safely remove subdirectories on the fly from dirs , which contains the list of the subdirectories to visit at each node.

Note that if you are in a directory, you can also get files corresponding to a simple pattern expression with glob.glob(pattern) . In this case you would have to substract the set of files to keep from the whole set, so the code above is more efficient.

import glob, os, multiprocessing p = multiprocessing.Pool(4) p.map(os.remove, glob.glob("P*.jpg")) 

Mind you this does not do recursion and uses wildcards (not regex).

UPDATE In Python 3 the map() function will return an iterator, not a list. This is useful since you will probably want to do some kind processing on the items anyway, and an iterator will always be more memory-efficient to that end.

If however, a list is what you really need, just do this:

. list(p.map(os.remove, glob.glob("P*.jpg"))) 

I agree it’s not the most functional way, but it’s concise and does the job.

map() is intended to transform a set of values, rather than run an arbitrary command on them. Therefore this is not the most recommended technique, and actually fails in Python 3 as map() now returns an iterable, rather than immediately evaluating the functions.

Please note that map returns a generator as of python 3 and this will not execute the function remove.

It’s not clear to me that you actually want to do any named-group matching — in the use you describe, the photoid is an input to the deletion function, and named groups’ purpose is «output», i.e., extracting certain substrings from the matched string (and accessing them by name in the match object). So, I would recommend a simpler approach:

import re import os def delete_thumbnails(photoid, photodirroot): matcher = re.compile(r'^%s\d+\D.*jpg$' % photoid) numdeleted = 0 for rootdir, subdirs, filenames in os.walk(photodirroot): for name in filenames: if not matcher.match(name): continue path = os.path.join(rootdir, name) os.remove(path) numdeleted += 1 return "Deleted %d thumbnails for %r" % (numdeleted, photoid) 

You can pass the photoid as a normal string, or as a RE pattern piece if you need to remove several matchable IDs at once (e.g., r’abc[def] to remove abcd, abce, and abcf in a single call) — that’s the reason I’m inserting it literally in the RE pattern, rather than inserting the string re.escape(photoid) as would be normal practice. Certain parts such as counting the number of deletions and returning an informative message at the end are obviously frills which you should remove if they give you no added value in your use case.

Others, such as the «if not . // continue» pattern, are highly recommended practice in Python (flat is better than nested: bailing out to the next leg of the loop as soon as you determine there is nothing to do on this one is better than nesting the actions to be done within an if ), although of course other arrangements of the code would work too.

Источник

Оцените статью