How do I delete a file or folder in Python?
Solution 1
os.remove()
removes a file.os.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.
Solution 2
Python syntax to delete a file
import os
os.remove("/tmp/<file_name>.txt")
Or
import os
os.unlink("/tmp/<file_name>.txt")
Or
pathlib Library for Python version >= 3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
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.
Best practice
- First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
a.os.path.isfile("/path/to/file")
b. Useexception handling.
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: ## Show an error ##
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 failed, report it back to 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
shutil.rmtree()
Example for shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= raw_input("Enter directory name: ")
## Try to remove tree; if failed show an error using try...except on screen
try:
shutil.rmtree(mydir)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
Solution 3
Use
shutil.rmtree(path[, ignore_errors[, onerror]])
(See complete documentation on shutil) and/or
os.remove
and
os.rmdir
(Complete documentation on os.)
Solution 4
Here is a robust function that uses both os.remove
and shutil.rmtree
:
def remove(path):
""" param <path> 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))
Solution 5
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()
Comments
-
Zygimantas almost 2 years
How do I delete a file or folder?
-
Ilya Serbis over 8 yearsos.rmdir() on Windows also removes directory symbolic link even if the target dir isn't empty
-
Paebbels about 8 yearsPlease add the pathlib interface (new since Python 3.4) to your list.
-
Kaz about 7 yearsI.e. 8 lines of code to simulate the ISO C
remove(path);
call. -
Lalithesh over 6 yearsThis will delete only the files inside the folder and subfolders leaving the folder structure intact..
-
Admin almost 6 yearsIf the file doesn't exist,
os.remove()
throws an exception, so it may be necessary to checkos.path.isfile()
first, or wrap in atry
. -
Pranasas almost 6 yearsWhat about a non-empty directory though?
-
MSeifert almost 6 years@Pranasas Unfortunately it seems there is nothing (natively) in
pathlib
that can handle deleting non-empty directories. However you could useshutil.rmtree
. It has been mentioned in several of the other answers so I haven't included it. -
mhsmith almost 6 years
shutil.rmtree
is not supposed to be asynchronous. However, it may appear to be on Windows with virus scanners interfering. -
Stein almost 6 years
rmtree(directory_path)
works in python 3.6.6 but not in python 3.5.2 - you needrmtree(str(directory_path)))
there. -
Ciro Santilli OurBigBook.com over 5 years@Kaz agreed annoying, but does remove deal with trees? :-)
-
dlewin over 5 yearsSubprocess is practice to avoid
-
merwok about 5 yearsException 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
-
Mark Amery almost 5 years@mhsmith Virus scanners? Is that wild speculation, or do you actually know that they can cause this effect? How on earth does that work if so?
-
Mark Amery almost 5 yearsI wouldn't recommend
subprocess
for this.shutil.rmtree
doesrm -r
's job just fine, with the added bonus of working on Windows. -
Neo li over 4 years
os.path.islink(file_path):
a bug, should beos.path.islink(path):
-
PedroA over 4 yearsjust for completion... the exception thrown by
os.remove()
if a file doesn't exist isFileNotFoundError
. -
Tiago Martins Peres about 4 years
shutil.rmtree()
removes not only the directory but also its content. -
user324747 about 4 yearsDoes
os.remove()
take multiple arguments to delete multiple files, or do you call it each time for each file? -
AO_ almost 4 yearsHave this mapped out already here: ao.gl/how-to-delete-a-file-in-python
-
jaaq over 3 years
-
Felix over 3 years@Jérôme I think
missing_ok=True
, added in 3.8 solves that! -
Petr Vepřek over 3 yearsos.removedirs removes a branch of empty directories (i.e. it first deletes empty leaf directory and then it continues up the branch hierarchy deleting all empty directories).
-
Welgriv almost 3 yearswhat's the point to catch the exception in the very last example ?
-
young_souvlaki over 2 yearsIf you opened the file in a
with
statement and assigned it tof
, you can issueos.remove(f.name)
within thewith
block. -
user171780 about 2 years@TiagoMartinsPeres how can you remove a directory but not it's content?
-
Tiago Martins Peres about 2 years@user171780 what should happen with the content then?