How do I delete a file or folder in Python?

  • 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.

Leave a Comment