Skip to main content

How to delete a file in Python

How to delete a file in Python.

Here's a detailed step-by-step tutorial on how to delete a file in Python:

Step 1: Import the os module

To delete a file in Python, you need to import the os module. The os module provides a way to interact with the operating system and perform various operations, including file deletion.

import os

Step 2: Specify the file path

Next, you need to specify the path of the file you want to delete. The file path should include the file name and its extension.

file_path = "path/to/file.txt"

Replace "path/to/file.txt" with the actual path of the file you want to delete.

Step 3: Check if the file exists

Before deleting the file, it's a good practice to check if the file exists. This prevents errors and ensures that you only delete the file if it actually exists.

if os.path.exists(file_path):
# File exists, proceed with deletion
pass
else:
# File doesn't exist, handle the error or raise an exception
pass

Step 4: Delete the file

Once you have verified that the file exists, you can delete it using the os.remove() function. This function takes the file path as an argument and deletes the file from the file system.

if os.path.exists(file_path):
os.remove(file_path)
print("File deleted successfully!")
else:
print("File not found!")

If the file is successfully deleted, the message "File deleted successfully!" will be printed. Otherwise, if the file is not found, the message "File not found!" will be printed.

Additional Steps:

Alternatively, you can use the os.unlink() function to delete a file. It works similarly to os.remove() and takes the file path as an argument.

if os.path.exists(file_path):
os.unlink(file_path)
print("File deleted successfully!")
else:
print("File not found!")

Delete an empty directory:

If you want to delete an empty directory, you can use the os.rmdir() function. This function removes an empty directory specified by its path.

directory_path = "path/to/directory"
if os.path.exists(directory_path):
os.rmdir(directory_path)
print("Directory deleted successfully!")
else:
print("Directory not found!")

Replace "path/to/directory" with the actual path of the directory you want to delete.

Delete a directory and its contents:

To delete a directory and all its contents (including files and subdirectories), you can use the shutil.rmtree() function from the shutil module.

import shutil

directory_path = "path/to/directory"
if os.path.exists(directory_path):
shutil.rmtree(directory_path)
print("Directory and its contents deleted successfully!")
else:
print("Directory not found!")

Replace "path/to/directory" with the actual path of the directory you want to delete.

That's it! You now have a step-by-step tutorial on how to delete a file in Python. Feel free to customize the code based on your specific requirements.