Python: Bulk delete files
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).
The provided Python script is designed to clean up files in subdirectories of a specified parent folder by deleting files that do not match a given string, such as '_bkgrd'. It iterates through each subfolder, checks if the items are directories, and then examines the files within those directories. If a file does not contain the specified suffix, the script prints a message indicating the file's deletion and removes it from the directory. This functionality is useful for organizing files, particularly in scenarios involving image processing or asset management.
import os
def delete_non_target_files(parent_folder, target_string):
# Iterate through each subfolder in the parent folder
for subfolder in os.listdir(parent_folder):
subfolder_path = os.path.join(parent_folder, subfolder)
# Check if it's a directory
if os.path.isdir(subfolder_path):
# Iterate through each file in the subfolder
for filename in os.listdir(subfolder_path):
file_path = os.path.join(subfolder_path, filename)
# Check if it's a file and doesn't contain the specified target string
if os.path.isfile(file_path) and target_string not in filename:
print(f"Deleting file: {file_path}")
os.remove(file_path) # Delete the file
# Specify the path to your folder and the target suffix
folder_path = 'path/to/folder'
target_string = '_bkgrd'
delete_non_target_files(folder_path, target_string)