3425

How can I delete a file or folder in Python?

0

18 Answers 18

4908

Use one of these methods:


On Python 3.3 and below, you can use these methods instead of the pathlib ones:

12
  • 9
    os.rmdir() on Windows also removes directory symbolic link even if the target dir isn't empty Commented Dec 18, 2015 at 17:23
  • 106
    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.
    – user1142217
    Commented Jul 4, 2018 at 0:00
  • 39
    just for completion... the exception thrown by os.remove() if a file doesn't exist is FileNotFoundError.
    – PedroA
    Commented Feb 4, 2020 at 17:52
  • Does os.remove() take multiple arguments to delete multiple files, or do you call it each time for each file?
    – user324747
    Commented May 9, 2020 at 23:57
  • 18
    @Jérôme I think missing_ok=True, added in 3.8 solves that!
    – Felix
    Commented Dec 8, 2020 at 21:04
759

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 if the file or folder exists and then delete it. You can achieve this in two ways:

  1. os.path.isfile("/path/to/file")
  2. Use exception 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:
    # 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

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 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))
3
129

Use

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

(See complete documentation on shutil) and/or

os.remove

and

os.rmdir

(Complete documentation on os.)

1
  • 9
    Please add the pathlib interface (new since Python 3.4) to your list.
    – Paebbels
    Commented Apr 25, 2016 at 19:38
101

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))
5
  • 16
    I.e. 8 lines of code to simulate the ISO C remove(path); call.
    – Kaz
    Commented Apr 21, 2017 at 23:22
  • 2
    @Kaz agreed annoying, but does remove deal with trees? :-) Commented Sep 8, 2018 at 22:37
  • 6
    os.path.islink(file_path): a bug, should be os.path.islink(path):
    – Neo li
    Commented Jan 23, 2020 at 9:17
  • Robust, well, it does not handle patterns, like "*.bak"...
    – karelv
    Commented Sep 28, 2023 at 17:12
  • Why not use glob: for p in glob.glob(path)
    – karelv
    Commented Sep 28, 2023 at 17:23
54

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 alias of remove().
  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: Remove a file using os.remove()

import os

os.remove("test_file.txt")

Example 2: Check if file exists using os.path.isfile() and delete it with os.remove()

import os

# check if file exist or not
if os.path.isfile("test.txt"):
    # remove the file
    os.remove("test.txt")
else:
    # Show the message instead of throwing an error
    print("File does not exist")

Example 3: 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.

import os, glob

# Loop over all files and delete them one by one
for file in glob.glob("pythonpool/*"):
    os.remove(file)
    print("Deleted " + str(file))

os.unlink()

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: Delete a file using shutil.rmtree()

import shutil 
import os 

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

pathlib.Path.rmdir() to remove empty directory

The 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, 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()
49

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()
2
  • 11
    What about a non-empty directory though?
    – Pranasas
    Commented Jul 11, 2018 at 8:43
  • 2
    @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
    Commented Jul 11, 2018 at 8:46
44

How do I delete a file or folder in Python?

For Python 3, to remove the file and directory individually, use the unlink and rmdir Path object methods respectively:

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

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:

from shutil import rmtree

rmtree(dir_path)

Demonstration

New in Python 3.4 is the Path object.

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"):

from pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()

and now:

>>> file_path.is_file()
True

Now let's delete them. First the file:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

We can use globbing to remove multiple files - first let's create a few files for this:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

Then just iterate over the glob pattern:

>>> for each_file_path in directory_path.glob('*.my'):
...     print(f'removing {each_file_path}')
...     each_file_path.unlink()
... 
removing ~/directory/foo.my
removing ~/directory/bar.my

Now, demonstrating removing the directory:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

What if we want to remove a directory and everything in it? For this use-case, use shutil.rmtree

Let's recreate our directory and file:

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'

Now, import rmtree and pass the directory to the funtion:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

and we can see the whole thing has been removed:

>>> 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:

$ pip install pathlib2

And then you can alias the library to pathlib

import pathlib2 as pathlib

Or just directly import the Path object (as demonstrated here):

from pathlib2 import Path

If that's too much, you can remove files with os.remove or os.unlink

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

or

unlink(join(expanduser('~'), 'directory/file'))

and you can remove directories with os.rmdir:

from os import rmdir

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.

1
  • rmtree(directory_path) works in python 3.6.6 but not in python 3.5.2 - you need rmtree(str(directory_path))) there.
    – Stein
    Commented Aug 22, 2018 at 8:48
11

This is my function for deleting dirs. The "path" requires the full pathname.

import os

def rm_dir(path):
    cwd = os.getcwd()
    if not os.path.exists(os.path.join(cwd, path)):
        return False
    os.chdir(os.path.join(cwd, path))

    for file in os.listdir():
        print("file = " + file)
        os.remove(file)
    print(cwd)
    os.chdir(cwd)
    os.rmdir(os.path.join(cwd, path))
10

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')
2
  • 1
    shutil.rmtree is not supposed to be asynchronous. However, it may appear to be on Windows with virus scanners interfering.
    – mhsmith
    Commented Aug 2, 2018 at 21:04
  • 1
    @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
    Commented Jul 4, 2019 at 23:02
8
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
  • 1
    This will delete only the files inside the folder and subfolders leaving the folder structure intact..
    – Lalithesh
    Commented Feb 28, 2018 at 11:30
7

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.

For deleting folders:

shutil.rmtree(path, ignore_errors=False, onerror=None)

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.

For deleting folders recursively towards parent:

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

3

To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

Since shutil.rmtree() will only remove directories and os.remove() or os.unlink() will only remove files.

2
  • 1
    shutil.rmtree() removes not only the directory but also its content. Commented Apr 30, 2020 at 8:22
  • State of Python skills at SO: Had to scroll all the way to here to find the first solution without the race.
    – heiner
    Commented Nov 13, 2023 at 21:58
3

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

0
2

To remove all files in folder

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 remove all folders in a directory

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))
2
import os

def del_dir(rootdir):
    for (dirpath, dirnames, filenames) in os.walk(rootdir):
        for filename in filenames: os.remove(rootdir+'/'+filename)
        for dirname in dirnames: del_dir(rootdir+'/'+dirname)
    os.rmdir(rootdir)
2

There is a simple and effective way to remove all files and directories using List Comprehension.

 import glob
 from os import path, remove, rmdir
 
 #The directory you wish to empty...
 your_dir = "/path/to/dir/with/contents"
 # Use list comprehension to ensure we don't compromise on speed
 [            
    remove(f) if path.isfile(f)
    else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)]
    for f in glob.glob(path.join(your_dir, "*"))
 ]

This is what it works:

  1. We first use glob to get all files and directories in the directory you want to empty. In this case, "your_dir" for f in glob.glob(path.join(your_dir, "*"))
  2. Then we remove any files within this "parent directory" remove(f) if path.isfile(f)
  3. This line else [remove(ff) for ff in glob.glob(path.join(f, "*"))] + [rmdir(f)] is the most interesting.
  • First, because these will be directories we empty them using the glob and remove combination [remove(ff) for ff in glob.glob(path.join(f, "*"))]
  • Now that the "child directory" is empty, we need rmdir to remove it. To do so, we use a hack; list concatenation. By adding + [rmdir(f)] we force python to evaluate rmdir(f) and thus remove the directory for us. Viola!
1

My prefered method os.walk and os.remove with list comprehension:

To delete all files in one directory:

import os
from os import walk

path1 = './mypath1/'

[os.remove(path1+ff) for ff in next(walk(path1), (None, None, []))[2]]

If you have various directories you want to delete all files:

import os
from os import walk

path1 = "./mypath1/"
path2 = "./mypath2/"
path3 = "./mypath3/"

for p in [path1,path2,path3]:
    [os.remove(p+ff) for ff in next(walk(p), (None, None, []))[2]]
1

Move file or directory under a temp directory and delete it. This will be also atomic

import os
import pathlib
import tempfile


def rm(path: str):
    """Remove file or directory"""
    _path = pathlib.Path(path).expanduser()
    with tempfile.TemporaryDirectory(dir=_path.parent) as _dir:
        _path.replace(os.path.join(_dir, _path.name))

Not the answer you're looking for? Browse other questions tagged or ask your own question.