How to delete a file or folder in Python?

Posted by Editorial Staff | Updated on

In this answer, We have shared how to delete a file or folder using Python. Use the following python code:

os.remove() removes a file.

os.rmdir() removes an empty directory.

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

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

  • pathlib.Path.unlink() removes a file or symbolic link.
  • pathlib.Path.rmdir() removes an empty directory.

If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers