Python Delete Files from Directory
When working on projects, there are frequently a ton of sample files or folders that you must delete because, after cleaning up your code base, they are no longer necessary. So, learning how to remove a file in Python is a must for all programmers. We'll go over the various approaches to deleting items from folders.
The following tools in Python let you carry out tasks of this nature:
We can use operating system-specific features thanks to the OS module.
Path: From pathlib extract the only variation between it and the OS module is that in this case we construct a Path object for a specific file to send it in function.
Shutil is a high-level program for file functions, so import it. On certain folders and file groupings, you can
The main difference between the OS module and the Shutil module is that the directory you want to delete in the OS module must be empty, whereas the directory and all of its contents can be destroyed in the Shutil module.
The best strategy is to make sure a file or folder is still there before removing it. then take the necessary steps to prevent mistakes. By using the following instructions, you can determine whether the file is present:
os.path.isfile("/path/to/file")
Implement exception handling (Try - Except block)
os.path.exists
Note: Exception handling is recommended over verifying because the file may have been removed or changed between the two lines.
In Python, how do you delete a file?
Here are 5 distinct Python techniques to delete a file from a directory:
First approach: os.remove(file_path)
A file whose path is provided can be deleted from the file system using the method os.remove(path). The location of the file you wish to delete is specified by a string named route. The file will be entirely erased if it is already there. It raises a FileNotFoundError exception if it doesn't.
Therefore, we always prefer to verify for file presence in order to prevent the mistake.
Example:
import os
from pathlib import Path
import touch
myfile = "favtutor.txt"
Path(myfile).touch() #creating a new empty file
print("Files in a directory -->",os.listdir())
print("We can see a file created succesfully")
print("-----------------------------------------------------")
# If file exists, delete it.
if os.path.isfile(myfile):
os.remove(myfile)
print("Favtutor file deleted using remove() function")
print("Current files in directory -->",os.listdir())
print("-----------------------------------------------------")
else:
# If it fails, inform the user.
print("Error: %s file not found" % myfile)
Output:
Files in a directory --> ['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
We can see a file created successfully
os.rmdir(directory_path), second method
A vacant directory can be eliminated from the file system using the os.rmdir(directory_path) method. The command "rmdir" stands for delete directory. This method will remove the directory if it is empty and the directory pointed to by directory_path exists.
If the directory is not empty, the procedure will throw an OSError exception with the message "Directory not empty."
Remember that you can give the relative path to the directory you want to remove inside the method if the directory is the same as your Python application; otherwise, you must input the complete path.
Example:
import pathlib
path="Text_files" # indicating the name of a new folder
If os.path.exists(path) is false: # checking to see whether a folder already exists # creating a new folder os.makedirs(path)
# loop to iterate working directory files and subdirectories for root, dirs, and # obtaining the working directory path rootdir=os.getcwd()
files in os.walk(top=rootdir, topdown=False):
for name in dirs:
dir_path=os.path.join(root, name)
print("Subdirectory",dir_path)
print("We can see a folder created succesfully with name Text_files")
print("-----------------------------------------------------")
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
new=os.path.join(dir_path,myfile)
Path(new).touch()
print("Files in a directory -->",os.listdir())
# Try to delete the empty folder
# checking for folder availaibility using try and except block
try:
os.rmdir(dir_path)
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
print("-----------------------------------------------------")
Output:
Subdirectory f:\projects\Favtutor\Text_files
We can see a folder created succesfully with name Text_files
Files in a directory --> ['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv', 'Text_files']
The rmdir() method fails to remove the directory because we added a new file with the name "Favtutor" inside of our newly formed subdirectory, prompting us with the error that the folder is not empty. Now that the file has been removed from our directory, let's attempt removing the subdirectory as well.
try:
os.remove(new)
print(new,"Favtutor file deleted using remove() function")
os.rmdir()
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
print("-----------------------------------------------------")
Output:
f:\projects\Favtutor\Text_files\favtutor.txt Using the remove() method, the favorite file was erased.
No subfolder folder was successfully removed.
The rmdir() method successfully removed the directory because it was now empty.
Shutil.rmtree (method 3), route, ignore_errors, and onerror
A directory and all of its components, including all subdirectories and files, can be deleted using the shutil.rmtree(path) method. There is an optional Boolean input called ignore_errors that determines whether or not any deletion-related mistakes should be disregarded. The fact that you can't use it to remove a single file is a significant disadvantage.
Since the directory wasn't empty in the case above, we can use the shutil() technique in lieu of rmdir() to fully and error-free remove the directory. The code will only be slightly altered, as seen below:
Example:
import pathlib
import shutil
path="Text_files" # specifiing new folder name
if not os.path.exists(path): # checking for folder existance
# creating a new folder
os.makedirs(path)
# fetching the working directory path
rootdir=os.getcwd()
#loop to iterate working directory files and subdirectory
for root, dirs, files in os.walk(top=rootdir, topdown=False):
for name in dirs:
dir_path=os.path.join(root, name)
print("Subdirectory",dir_path)
print("We can see a folder created succesfully with name Text_files")
print("-----------------------------------------------------")
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
new=os.path.join(dir_path,myfile)
Path(new).touch()
print("favtutor.txt file created inside Text_files directory")
print("-----------------------------------------------------")
# Try to delete the empty folder
# checking for folder availaibility using try and except block
try:
shutil.rmtree(path)
for root, dirs, files in os.walk(top=rootdir, topdown=False):
if dirs==[]:
print("No subdiretectory")
else:
print(dirs)
print("We can see a folder deleted succesfully")
print("-----------------------------------------------------")
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
print("-----------------------------------------------------")
Output:
Subdirectory f:\projects\Favtutor\Text_files
We can see a folder created succesfully with name Text_files
favtutor.txt file created inside Text_files directory
No subdiretectory
Pathlib.Path.unlink(missing_ok=False) (method 4)
A Path object that indicates the path of the file you want to delete is used by the pathlib.Path.unlink() function. The unlink() function will delete the file if it already exists, as indicated by the Path object.
If the file doesn't exist, a FileNotFoundError is triggered if the missing_ok parameter's default value of false is used. FileNotFoundError errors will not be handled if it is true.
With "Path.cwd," you can determine your current working location.
Example:
import pathlib
import os
path_object = Path(".")
print(type(path_object))
#creating a new empty file into a subdirectory
myfile = "favtutor.txt"
Path(myfile).touch()
print("favtutor.txt file created")
print(os.listdir())
print("-----------------------------------------------------")
file = pathlib.Path("favtutor.txt")
file.unlink(missing_ok=False)
print(os.listdir())
print("favtutor.txt file deleted")
Output:
<class 'pathlib.WindowsPath'>
favtutor.txt file created
['demo.txt', 'favtutor.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
['demo.txt', 'jupyter.ipynb', 'SPAM text message 20170820 - Data.csv']
favtutor.txt file deleted
Pathlib.Path.rmdir (method 5)()
We find it beneficial to delete unused directories. Prior to calling the rmdir() procedure on that route, you must pick the route() for the empty directory using the Path() function. It'll examine the folder's capacity.
The will be properly removed if it is zero bytes, or empty, otherwise an error is raised. It's safe to delete empty files using this method because no real data will be lost.
It is comparable to the os.rmdir() technique; however, the syntax is written differently. You can simply substitute this function for the os.rmdir(dir_path) line.
Path(dir_path).rmdir()
Python Issues with File Removal
Let's examine some of the typical issues that you might experience when removing folders in Python. Here is a Python script to remove all folders with a particular extensions.
import os
path="Text_files" # specifiing new folder name
if not os.path.exists(path): # checking for folder existance
# creating a new folder
os.makedirs(path)
files=["python.txt","data.csv","java.txt","house_prediction.xls","C.txt"]
for file in files:
new=os.path.join(path+"\\"+file)
# print(new)
# creating 5 new files inside Text_files folder
Path(new).touch()
print("Files in a directory -->",os.listdir(path))
for file_name in os.listdir(path):
if file_name.endswith('.txt'):
os.remove(path + "\\"+file_name)
print("Files deleted-->",path + "\\"+file_name)
print("Files in a directory -->",os.listdir(path))
Output:
Files in a directory --> ['C.txt', 'data.csv', 'house_prediction.xls', 'java.txt', 'python.txt']
Files deleted--> Text_files\C.txt
Files deleted--> Text_files\java.txt
Files deleted--> Text_files\python.txt
Files in a directory --> ['data.csv', 'house_prediction.xls']
A different Python program that deletes a file after reading its contents is provided here:
filepath="demo.txt"
f = open(filepath, "r")
print("contents of file")
print(f.read())
print("---------------------------------------------------------------------")
f.close()
os.remove("demo.txt")
print("File deleted succesfully")
Output:
Files in a directory --> ['C.txt', 'data.csv', 'house_prediction.xls', 'java.txt', 'python.txt']
Files deleted--> Text_files\C.txt
Files deleted--> Text_files\java.txt
Files deleted--> Text_files\python.txt
Files in a directory --> ['data.csv', 'house_prediction.xls']
A different Python program that deletes a file after reading its contents is provided here:
filepath="demo.txt"
f = open(filepath, "r")
print("contents of file")
print(f.read())
print("---------------------------------------------------------------------")
f.close()
os.remove("demo.txt")
print("File deleted succesfully")
Output:
Files in a directory --> ['C.txt', 'data.csv', 'house_prediction.xls', 'java.txt', 'python.txt']
Files deleted--> Text_files\C.txt
Files deleted--> Text_files\java.txt
Files deleted--> Text_files\python.txt
Files in a directory --> ['data.csv', 'house_prediction.xls']
A different Python program that deletes a file after reading its contents is provided here:
filepath="demo.txt"
f = open(filepath, "r")
print("contents of file")
print(f.read())
print("---------------------------------------------------------------------")
f.close()
os.remove("demo.txt")
print("File deleted succesfully")
Output:
Files in a directory --> ['C.txt', 'data.csv', 'house_prediction.xls', 'java.txt', 'python.txt']
Files deleted--> Text_files\C.txt
Files deleted--> Text_files\java.txt
Files deleted--> Text_files\python.txt
Files in a directory --> ['data.csv', 'house_prediction.xls']
A different Python program that deletes a file after reading its contents is provided here:
filepath="demo.txt"
f = open(filepath, "r")
print("contents of file")
print(f.read())
print("---------------------------------------------------------------------")
f.close()
os.remove("demo.txt")
print("File deleted succesfully")
Output:
contents of file
technology training
The term "technology" was only coined in the early 20th century, even though the man had been tinkering with science for centuries. The German words "Technik" and "Technologie" served as its inspiration. Although there is a distinction between "technik" and "technologie" in German, the English amalgamated the two words and began using the term "technology" in the 1930s.
The original definition of technology was provided in 1937 by American sociologist Read Bain in his journal "Technology and State Government." As well as the processes we employ to make them, Bain said that all tools, machinery, equipment, clothing, and other items are products of technology.
It would have taken a few days or maybe weeks a few of centuries ago. The advancement of technology has made life easier, more convenient, and safer than ever before. Although there are certain benefits to technology, there are also some drawbacks. Today, we rely on technology so heavily that it would be hard to survive even one day without it.
---------------------------------------------------------------------
Successfully removed a file
It's also crucial to understand how to overwrite a file in Python. convenient. Before contemporary technology, doing daily tasks was highly laborious and challenging. Just a few miles' worth of travel would need a whole day. Additionally, sending messages wasn't as simple as it is now. With a technology device like a cell phone
Get rid of all files in a directory
On occasion, we want to remove every item from a location without erasing the directory itself. To eliminate all items from a directory, follow the procedures listed below.
Utilize the os.listdir(path) method to get a list of the items in a folder. The titles of the files and directories in the specified directory are returned in a list.
Use a for loop to iterate through the collection and view each file one at a time.
Use the os.remove command to delete each file.()
import os
path = r"E:\demos\files\reports\\"
for file_name in os.listdir(path):
# construct full file path
file = path + file_name
if os.path.isfile(file):
print('Deleting file:', file)
os.remove(file)
Using rmdir, remove an empty directory (folder)
While a directory always contains some files, occasionally there are also vacant folders or groups that are no longer required.
The rmdir() function, which is present in both the pathlib and os modules, can be used to remove them.
employing the os.rmdir() function
The rmdir() method from the os package can be used to remove empty directories.
path, *, dir_fd = None, os.rmdir
The criteria that we must supply to this technique are as follows.
path - A string-formatted relative or exact route for the directory object.
The file location is dir_fd. None is the usual value, and in the event of an absolute route, this value is disregarded.
Note: In the event that the listing
import os
# Deleting an empty folder
directory = r"E:\pynative\old_logs"
os.rmdir(directory)
print("Deleted '%s' directory successfully" % directory)
Output
Deleted 'E:\pynative\old_logs' directory successfully
Implement pathlib.Path.rmdir()
The pathlib module's rmdir() function can also be used to eliminate or delete an empty directory.
Set the directory's name first.
Next, execute that path's rmdir() function.
Let's look at an illustration of how to delete the vacant "Images" directory.
import pathlib
# Deleting an empty folder
empty_dir = r"E:\pynative\old_images"
path = pathlib.Path(empty_dir)
"Deleted '%s' directory successfully"% empty_dir, path.rmdir() print
You may eliminate a Non-Empty Directory using Shutil.
On sometimes, we have to delete the whole contents of a subfolder. The rmtree() method of a shutil module may be used to delete a directory together with all of its contents. see delete a non-empty subdirectory in Python.
The shutil module in Python makes it easier to carry out high-level actions on a file or group of files, like transferring or deleting content.