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 os.remove(filename)
function.
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)