How Do I Delete a File or Folder in Python?

How Do I Delete a File or Folder in Python?

How do I delete a file or folder?

0

15 Answers


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

8

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.