How To Delete A File or Folder?: 12 Answers
How To Delete A File or Folder?: 12 Answers
2145
301
3336
Path objects from the Python 3.4+ pathlib module also expose these instance methods:
5 os.rmdir() on Windows also removes directory symbolic link even if the target dir isn't empty – Lu55 Dec 18 '15 at 17:23
8 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 . – Ben Crowell Jul 4 '18 at 0:00
2 I wish Path.unlink 1/ was recursive 2/ add an option to ignore FileNotfoundError. – Jérôme Jul 10 '18 at 13:52
7 just for completion... the exception thrown by os.remove() if a file doesn't exist is FileNotFoundError . – PedroA Feb 4 at 17:52
Does os.remove() take multiple arguments to delete multiple files, or do you call it each time for each file? –
UbuntuForums_Staff_Are_Trolls May 9 at 23:57
290
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy
Policy, and our Terms of Service.
Python syntax to delete a file
import os
os.remove("/tmp/<file_name>.txt")
Or
import os
os.unlink("/tmp/<file_name>.txt")
Or
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
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
1. 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. Use exception handling.
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
Exception Handling
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
RESPECTIVE OUTPUT
shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
13 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 – Éric Araujo May
22 '19 at 21:37
83
Use
os.remove
and
os.rmdir
6 Please add the pathlib interface (new since Python 3.4) to your list. – Paebbels Apr 25 '16 at 19:38
38
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))
8 I.e. 8 lines of code to simulate the ISO C remove(path); call. – Kaz Apr 21 '17 at 23:22
2 @Kaz agreed annoying, but does remove deal with trees? :-) – Ciro Santilli 冠状病毒审查六四事件法轮功 Sep 8 '18 at 22:37
32
You can use the built-in pathlib module (requires Python 3.4+, but there are backports for older versions on PyPI:
pathlib , pathlib2 ).
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
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. – MSeifert Jul 11 '18 at
8:46
29
For Python 3, to remove the file and directory individually, use the unlink and rmdir Path object methods respectively:
Note that you can also use relative paths with Path objects, and you can check your current working directory with
Path.cwd .
For removing individual files and directories in Python 2, see the section so labeled below.
To remove a directory with contents, use shutil.rmtree , and note that this is available in Python 2 and 3:
rmtree(dir_path)
Demonstration
Let's use one to create a directory and file to demonstrate usage. Note that we use the / to join the parts of the path,
this works around issues between operating systems and issues from using backslashes on Windows (where you'd need
to either double up your backslashes like \\ or use raw strings, like r"foo\bar" ):
and now:
>>> file_path.is_file()
True
We can use globbing to remove multiple files - first let's create a few files for this:
What if we want to remove a directory and everything in it? For this use-case, use shutil.rmtree
file_path.parent.mkdir()
file_path.touch()
and note that rmdir fails unless it's empty, which is why rmtree is so convenient:
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'
>>> directory_path.exists()
False
Python 2
If you're on Python 2, there's a backport of the pathlib module called pathlib2, which can be installed with pip:
If that's too much, you can remove files with os.remove or os.unlink
remove(join(expanduser('~'), 'directory/file'))
or
unlink(join(expanduser('~'), 'directory/file'))
rmdir(join(expanduser('~'), 'directory'))
Note that there is also a os.removedirs - it only removes empty directories recursively, but it may suit your use-case.
rmtree(directory_path) works in python 3.6.6 but not in python 3.5.2 - you need rmtree(str(directory_path))) there. – Stein
Aug 22 '18 at 8:48
4
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
1 This will delete only the files inside the folder and subfolders leaving the folder structure intact.. – Lalithesh Feb 28 '18 at 11:30
shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while...loop
import os
import shutil
shutil.rmtree(path)
while os.path.exists(path):
pass
print('done')
1 shutil.rmtree is not supposed to be asynchronous. However, it may appear to be on Windows with virus scanners interfering. –
mhsmith Aug 2 '18 at 21:04
@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 Jul 4 '19 at 23:02
2
For deleting files:
os.unlink(path, *, dir_fd=None)
or
os.remove(path, *, dir_fd=None)
Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is
directory, then exception is raised.
or
os.rmdir(path, *, dir_fd=None)
In order to remove whole directory trees, shutil.rmtree() can be used. os.rmdir only works when the directory is empty
and exists.
os.removedirs(name)
It remove every empty parent directory with self until parent which has some content
ex. os.removedirs('abc/xyz/pqr') will remove the directories by order 'abc/xyz/pqr', 'abc/xyz' and 'abc' if they are
empty.
For more info check official doc: os.unlink , os.remove , os.rmdir , shutil.rmtree , os.removedirs
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv
files in folder
for file in files:
os.remove(file)
To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:
Since shutil.rmtree() will only remove directories and os.remove() or os.unlink() will only remove files.
shutil.rmtree() removes not only the directory but also its content. – Tiago Martins Peres 李⼤仁 Apr 30 at 8:22
-1
I recommend using subprocess if writing a beautiful and readable code is your cup of tea:
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
And if you are not a software engineer, then maybe consider using Jupyter; you can simply type bash commands:
!rm -r my_dir
import shutil
shutil.rmtree(my_dir)
3 I wouldn't recommend subprocess for this. shutil.rmtree does rm -r 's job just fine, with the added bonus of working on
Windows. – Mark Amery Jul 4 '19 at 23:04