Python Delete File

Delete File

To delete a file, you must import the OS module and run its os.remove() Function:

Example

Delete file "demofile.txt":

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

Check if the file exists

To avoid errors, you may need to check if the file exists before trying to delete the file:

Example

Check if the file exists and then delete it:

import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

Delete File

To delete an entire folder, please use os.rmdir() Method:

Example

Delete folder "myfolder":

import os
os.rmdir("myfolder")

Tip:You can only delete empty folders.