Python Logo

Delete File


To delete a file in Python, you can use the os.remove() function. The os.remove() function takes the path to the file as an argument and deletes the file.

 

Python

import os

# Delete the file "myfile.txt"
os.remove("myfile.txt")
 

If the file does not exist, the os.remove() function will raise a FileNotFoundError exception.

 

Python

try:
    os.remove("myfile.txt")
except FileNotFoundError as e:
    print("File does not exist:", e)
 

You can also use the os.rmdir() function to delete an empty directory.

 

Python

import os

# Delete the empty directory "my_directory"
os.rmdir("my_directory")
 

If the directory is not empty, the os.rmdir() function will raise a OSError exception.

 

Python

try:
    os.rmdir("my_directory")
except OSError as e:
    print("Directory is not empty:", e)
 

To delete a directory and all of its contents, you can use the shutil.rmtree() function.

 

Python

import shutil

# Delete the directory "my_directory" and all of its contents
shutil.rmtree("my_directory")
 

Example:

 

Python

import os

# Delete the file "myfile.txt"
os.remove("myfile.txt")

# Delete the empty directory "my_directory"
os.rmdir("my_directory")

# Delete the directory "my_directory_with_contents" and all of its contents
shutil.rmtree("my_directory_with_contents")
 

This code will delete the file "myfile.txt", the empty directory "my_directory", and the directory "my_directory_with_contents" and all of its contents.