Python - How to delete a file

By xngo on June 16, 2019

In Python, deleting a file is easy. You simply run the following code.

import os
os.remove("my-document.docx")

You may want to remove other items such as a directory or everything from some directory. Here are some examples.

# Remove an empty directory.
#   If the directory contains some files, then it will throw an error.
import os
os.rmdir("somedir")
 
 
# Remove everything from a directory.
import shutil
shutil.rmtree("somedir")

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.