How do I delete a file or folder in Python?

2,717,911

Solution 1


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

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

  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.

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()
Share:
2,717,911
Zygimantas
Author by

Zygimantas

I'am beginner of python programming life...

Updated on July 08, 2022

Comments

  • Zygimantas
    Zygimantas almost 2 years

    How do I delete a file or folder?

  • Ilya Serbis
    Ilya Serbis over 8 years
    os.rmdir() on Windows also removes directory symbolic link even if the target dir isn't empty
  • Paebbels
    Paebbels about 8 years
    Please add the pathlib interface (new since Python 3.4) to your list.
  • Kaz
    Kaz about 7 years
    I.e. 8 lines of code to simulate the ISO C remove(path); call.
  • Lalithesh
    Lalithesh over 6 years
    This will delete only the files inside the folder and subfolders leaving the folder structure intact..
  • Admin
    Admin almost 6 years
    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.
  • Pranasas
    Pranasas almost 6 years
    What about a non-empty directory though?
  • MSeifert
    MSeifert almost 6 years
    @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.
  • mhsmith
    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
    Stein almost 6 years
    rmtree(directory_path) works in python 3.6.6 but not in python 3.5.2 - you need rmtree(str(directory_path))) there.
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com over 5 years
    @Kaz agreed annoying, but does remove deal with trees? :-)
  • dlewin
    dlewin over 5 years
    Subprocess is practice to avoid
  • merwok
    merwok about 5 years
    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
  • Mark Amery
    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
    Mark Amery almost 5 years
    I wouldn't recommend subprocess for this. shutil.rmtree does rm -r's job just fine, with the added bonus of working on Windows.
  • Neo li
    Neo li over 4 years
    os.path.islink(file_path): a bug, should be os.path.islink(path):
  • PedroA
    PedroA over 4 years
    just for completion... the exception thrown by os.remove() if a file doesn't exist is FileNotFoundError.
  • Tiago Martins Peres
    Tiago Martins Peres about 4 years
    shutil.rmtree() removes not only the directory but also its content.
  • user324747
    user324747 about 4 years
    Does os.remove() take multiple arguments to delete multiple files, or do you call it each time for each file?
  • AO_
    AO_ almost 4 years
    Have this mapped out already here: ao.gl/how-to-delete-a-file-in-python
  • jaaq
    jaaq over 3 years
    Also EAFP is preferred over LBYL in Python.
  • Felix
    Felix over 3 years
    @Jérôme I think missing_ok=True, added in 3.8 solves that!
  • Petr Vepřek
    Petr Vepřek over 3 years
    os.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
    Welgriv almost 3 years
    what's the point to catch the exception in the very last example ?
  • young_souvlaki
    young_souvlaki over 2 years
    If you opened the file in a with statement and assigned it to f, you can issue os.remove(f.name) within the with block.
  • user171780
    user171780 about 2 years
    @TiagoMartinsPeres how can you remove a directory but not it's content?
  • Tiago Martins Peres
    Tiago Martins Peres about 2 years
    @user171780 what should happen with the content then?