Python Delete Files
File deletion removes a file from disk.
Remove a file
remove() deletes the file. The checks prove it was there, then gone.
import os
with open("temp.txt", "w") as f:
f.write("bye")
print(os.path.exists("temp.txt"))
os.remove("temp.txt")
print(os.path.exists("temp.txt"))Check first, then remove
The if check guards the remove call. A missing file just prints a message.
import os
if os.path.exists("temp.txt"):
os.remove("temp.txt")
print("deleted")
else:
print("nothing to delete")Remove an empty folder
rmdir() deletes one empty folder. Files inside would block it.
import os
if not os.path.exists("empty_box"):
os.mkdir("empty_box")
os.rmdir("empty_box")
print(os.path.exists("empty_box"))The risky line
This line raises FileNotFoundError if ghost.txt is missing. Always check first, as shown above.
import os
os.remove("ghost.txt")Example
import os
with open("temp.txt", "w") as f:
f.write("Temporary note.\n")
print(os.path.exists("temp.txt"))
os.remove("temp.txt")
print(os.path.exists("temp.txt"))Key points
- Use os.remove() to delete one file
- Deleting removes a file from disk for good.
- Check os.path.exists() first.
- Removing a missing file raises FileNotFoundError.
- Use os.rmdir() to delete one folder
- os.rmdir() works only on empty folders
- Use os.mkdir() to make a folder.
In this example, the program creates a temp file with one line. The first exists() check prints True, so the file is there. remove() then deletes the file. The second exists() check prints False. The False answer proves the file is gone.
Note
Deleting is final here.
Files removed this way do not go to a trash folder.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What should you do before calling os.remove() on a file?