Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How can I delete a file or folder in Python?

Solution:

If you want to delete files in Python, you can use functions from Python’s built-in OS module.

  • To delete a file: os.remove().
  • To delete an empty folder: os.rmdir()

However, if it’s not an empty folder, you must use the rmtree() function from the shutil module.


import os , shutil

os.remove("unwanted-file.txt")
os.rmdir("empty-dir")
shutil.rmtree("nonempty-dir")

These functions, however, will fail if the file or directory to be removed does not exist. We can prevent this by using os.path.isfile() and os.path.isdir() to check for the existence of files and directories before deleting them:


import os, shutil

if os.path.isfile("unwanted-file.txt")
     os.remove("unwanted-file.txt")

if os.path.isdir("empty-dir")
     os.rmdir("empty-dir")

if os.path.isdir("nonempty-dir")
     shutil.rmtree("nonempty-dir")

For more such Python tricks, follow MarsDevs blogs.