Many a times, we come across deleting old files like logs, deprecated files from file system
We come across scenarios like
To delete logs older than x days
To delete txt files older than x days
Let us discuss how we can achieve deleting old files using python script
What does the script do?
It will take the path from where you need to delete the txt files
The below program checks the time stamp of the files and deletes the txt files older than 7 days.
You can change the file extension, folder path and use it.
folder_path = "C:\Files_To_Read"
file_ends_with = ".txt"
how_many_days_old_logs_to_remove = 7
How to call the script?
python delete_old_logs.py
delete_old_logs.py
import os, time, sys folder_path = "C:\Files_To_Read" file_ends_with = ".txt" how_many_days_old_logs_to_remove = 7 now = time.time() only_files = [] for file in os.listdir(folder_path): file_full_path = os.path.join(folder_path,file) if os.path.isfile(file_full_path) and file.endswith(file_ends_with): #Delete files older than x days if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400: os.remove(file_full_path) print "\n File Removed : " , file_full_path
This is exactly what I was looking for. Thanks a lot.
ReplyDeleteDoes this program deletes image files
ReplyDeleteSuper helpful Thanks!
ReplyDelete