Bootstrap FreeKB - Python (Scripting) - Remove or Delete file or directory
Python (Scripting) - Remove or Delete file or directory

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 2e6437 in the box below so that we can be sure you are a human.