Last Updated : 14 Dec, 2023
Summarize
Comments
Improve
When any large program is created, usually there are small files that we need to create to store some data that is needed for the large programs. when our program is completed, so we need to delete them. In this article, we will see how to delete a file in Python.
Methods to Delete a File in Python
- Python Delete File using os. remove
- Delete file in Python using the send2trash module
- Python Delete File using os.rmdir
Check if the file exists or not
Command to install OS Module:
pip3 install os
For Delete a File in Python, you can use the os.path.exists()
function to check if a file exists. Here’s a simple example: Replace '
path/to/your/file.txt
'
with the actual path of the file you want to check. The os.path.exists()
function returns True
if the file exists and False
otherwise. The code then prints a message based on the existence of the file.
Python3
import
os
def
check_file_existence(file_path):
if
os.path.exists(file_path):
print
(f
'The file "{file_path}" exists.'
)
else
:
print
(f
'The file "{file_path}" does not exist.'
)
# Example usage:
file_path
=
'path/to/your/file.txt'
check_file_existence(file_path)
Output :
The file "path/to/your/file.txt" does not exist.
Delete a File in Python using ‘os.remove’
We will be importing the OS library and going to use the os.remove() function to remove the desired file.
Example 1: Delete the file from your current directory
This is the simple code to delete the file from your current directory.
Python3
import
os
os.remove(
"starwars.txt"
)
Example 2: Detailed Explanation
In below code Python script prompts the user to input a filename for deletion. If the input is ‘quit’, the program exits; otherwise, it attempts to remove the specified file using `os.remove()`. A success message is then printed.
Python3
import
os
print
(
"Enter 'quit' for exiting the program"
)
filename
=
input
('Enter the name of the
file
, \
that
is
to be deleted : ')
if
filename
=
=
'quit'
:
exit()
else
:
print
(
'\nStarting the removal of the file !'
)
os.remove(filename)
print
(
'\nFile, '
, filename, 'The
file
deletion \
is
successfully completed !!')
Output:
The desired file to be deleted:
A sample run of the program
When we enter the name of the file to be deleted:
The deletion:
The Working Output:
Delete a Files in Python using send2trash Module
We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.txt’ files in the given directory.
Example : In this script walks through files in the directory ‘/Users/tithighosh/Documents’ using `os.walk`. For each ‘.txt’ file found, it prints its path and uses `send2trash` to move it to the system trash, avoiding permanent deletion. The script effectively trashes all ‘.txt’ files in the specified directory and its subdirectories.
Python3
import
os
import
send2trash
# walking through the directory
for
folder, subfolders, files
in
os.walk(
'/Users/tithighosh/Documents'
):
for
file
in
files:
# checking if file is of .txt type
if
file
.endswith(
'.txt'
):
path
=
os.path.join(folder,
file
)
# printing the path of the file
# to be deleted
print
(
'deleted : '
, path )
# deleting the file
send2trash.send2trash(path)
Output:
deleted : /Users/tithighosh/Documents/cfile.txtdeleted : /Users/tithighosh/Documents/e_also_big_output.txtdeleted : /Users/tithighosh/Documents/res.txtdeleted : /Users/tithighosh/Documents/tk.txt
Python a Delete File using os.rmdir
In the os.rmdir
method removes an empty directory specified by the given path. It is important to note that if the directory contains any files or subdirectories, the method will raise an OSError. Therefore, it’s essential to ensure that the directory is empty before using this method.
Example : In this example, replace 'path/to/empty_directory'
with the actual path of the empty directory you want to delete. The delete_empty_directory
function attempts to remove the specified directory using os.rmdir
and prints a success message if the deletion is successful
Python3
import
os
def
delete_empty_directory(directory_path):
try
:
os.rmdir(directory_path)
print
(f
'The directory "{directory_path}" has been successfully deleted.'
)
except
OSError as e:
print
(f
'Error: {e}'
)
# Example usage:
directory_to_delete
=
'path/to/empty_directory'
delete_empty_directory(directory_to_delete)
Output :
The directory "path/to/empty_directory" has been successfully deleted.
Related Article
Delete a directory or file using Python
How to delete data from file in Python
Delete files older than N days in Python