How to delete a file or folder in Python? How to delete a file or folder in Python? python python

How to delete a file or folder in Python?

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

Python syntax to delete a file

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


import osos.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/pythonimport osmyfile="/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/pythonimport 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.txtError: demo.txt - No such file or directory.Enter file name to delete : rrr.txtError: rrr.txt - Operation not permitted.Enter file name to delete : foo.txt

Python syntax to delete a folder


Example for shutil.rmtree()

#!/usr/bin/pythonimport osimport sysimport shutil# Get directory namemydir= raw_input("Enter directory name: ")## Try to remove tree; if failed show an error using try...except on screentry:    shutil.rmtree(mydir)except OSError as e:    print ("Error: %s - %s." % (e.filename, e.strerror))


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

(See complete documentation on shutil) and/or




(Complete documentation on os.)