How to delete a file or folder in Python?

ID : 228

viewed : 101

Tags : pythonfile-iodirectorydelete-filepython

Top 5 Answer for How to delete a file or folder in Python?

vote vote


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

vote vote


Python syntax to delete a file

import os os.remove("/tmp/<file_name>.txt") 


import os os.unlink("/tmp/<file_name>.txt") 


pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.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.

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


 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


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)) 
vote vote



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

(See complete documentation on shutil) and/or




(Complete documentation on os.)

vote vote


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)) 
vote vote


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() 

Top 3 video Explaining How to delete a file or folder in Python?