Python (Scripting) - Remove or Delete file or directory
by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
os.remove can be used to remove a file or directory. Here is the minimal boilterplate code without error handling.
#!/usr/bin/python3
import os
os.chown(f"/path/to/file", 1001, 2001)
Here is a more practical example, with try/except/else error handling
#!/usr/bin/python3
import os
target_file = "/tmp/foo.txt"
try:
os.remove(target_file)
except Exception as exception:
print(f"got the following exception: {exception}")
else:
if os.path.exists(target_file):
print(f"{target_file} still exists")
else:
print(f"{target_file} was successfully removed")
Did you find this article helpful?
If so, consider buying me a coffee over at