How to Delete a File in Python


A quick solution in Python

import os
os.remove("filename.txt")

The above code will delete a file in Python, it will not however delete a directory, or a directory containing files. For this we will need to explore a bit more..

Check file exists before deleting

First check if the file exists before deleting it:

import os

if os.path.exists("filename.txt"):
  os.remove("filename.txt")
else:
  print("The file doesn't exist")

Delete a directory/folder

Sometimes you may want to delete an entire folder as well:

import os
os.rmdir("foldername")

What options are available?

#removes a file.
os.remove()

#removes an empty directory.
os.rmdir()

#deletes a directory and all its contents.
shutil.rmtree()

Using Pathlib as an alternative

As of Python 3.4+, you can also use pathlib as follows:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

rmdir is also available to remove a blank directory:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()