How to delete a file in Python

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

First check if the file exists before deleting it:

import os

if os.path.exists("filename.txt"):
  os.remove("filename.txt")
else:
  print("The file doesn't exist")

Sometimes you may want to delete an entire folder as well:

import os
os.rmdir("foldername")
Tags:

Leave a Reply

Your email address will not be published.