Low Orbit Flux Logo 2 F

Python How To Delete A File

Python makes it easy to delete files. You can delete them with a single fuction call or you could optionally check if the file exists first. Just be careful especially when passing a variable to this function. If the variable holds an unexpected value it could cause a log of damage and delete files that you did not intend to remove.

To delete a file with Python use the following:


import os
os.remove("myfile.txt")

If you want to check if a file exists first you can use the “os.path.exists()” method like this:


import os
if os.path.exists("myfile.txt"):
  os.remove("myfile.txt")

You could also specify a full, absolute path if you like:


os.remove("/home/user/myfile.txt")

If you want to remove a directory you can use the following.


os.rmdir("dir1")