How to delete a file in Python

A quick solution in Python

import os os.remove("filename.txt")
Code language: Python (python)

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")
Code language: Python (python)

Delete a directory/folder

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

import os os.rmdir("foldername")
Code language: Python (python)

What options are available?

#removes a file. os.remove() #removes an empty directory. os.rmdir() #deletes a directory and all its contents. shutil.rmtree()
Code language: Python (python)

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()
Code language: Python (python)

rmdir is also available to remove a blank directory:

import pathlib path = pathlib.Path(name_of_folder) path.rmdir()
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments