How do I delete a file or folder?
15 Answers
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.
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()