Python Delete File
To delete a file in Python, import the
os module with
import os and run
os.remove(filename) in your script.
The following code removes the file
'file.dat' from the current folder assuming the Python script resides in the same directory:
import os os.remove('file.dat')
Python Delete Files in Folder
To delete a folder or directory with all of the files in it, import the
shutil module with
import shutil and run
shutil.rmtree(folder_name). The string argument
folder_name is the name and path of the folder to be deleted.
import shutil shutil.rmtree('my_folder')
Python Delete File shutil
It is not possible to remove an individual file using the
shutil module because it focuses on high-level operations on multiple files. If you want to remove an individual file, use the
os module and its
import os os.remove('my_file.txt')
Python Delete Files Wildcard
To remove files by matching a wildcard pattern such as
'*.dat', first obtain a list of all file paths that match it using
glob.glob(pattern). Then iterate over each of the filenames in the list and remove the file individually using
os.remove(filename) in a for loop.
Here’s an example:
import glob, os # Get all files with suffix jpg files = glob.glob('*.jpg') # Iterate over the list of files and remove individually for file in files: os.remove(file)
Python Delete Files in Folder with Extension
A similar problem is to remove all files in a given folder that have a certain extension or suffix.
To remove all files in a
folder with a given suffix such as
.dat, use the wildcard pattern
'*.dat' to obtain a list of all matching file paths with
glob.glob('*.dat'). Then iterate over each of the filenames in the list and remove each file individually using
os.remove(folder + filename) in a for loop.
Here’s an example:
import glob, os folder = '/your/path/folder/' # Get all files with suffix files = glob.glob('*.dat') # Iterate over the list of files and remove individually for file in files: os.remove(folder + file)
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.