Python – How to Delete a File or Folder delete-filedirectoryfile-iopython How can I delete a file or folder in Python? Best Answer Use one of these methods: pathlib.Path.unlink() removes a file or symbolic link. pathlib.Path.rmdir() removes an empty directory. shutil.rmtree() deletes a directory and all its contents. On Python 3.3 and below, you can use these methods instead of the pathlib ones: os.remove() removes a file. os.unlink() removes a symbolic link. os.rmdir() removes an empty directory. Related SolutionsPython Folder Contents – How to Delete the Contents of a Folder Using Python import os, shutil folder = '/path/to/folder' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) Related Question
Best Answer
Use one of these methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.On Python 3.3 and below, you can use these methods instead of the
pathlib
ones:os.remove()
removes a file.os.unlink()
removes a symbolic link.os.rmdir()
removes an empty directory.