Deleting Files in Windows with Python
pythonHere’s a Python script to delete files that are older than 7 days. If you don’t have a lot of files to sort through, it’s possible to do it in the command line with forfiles. However, in my case, I had over 1.6 million files and I wasn’t able to delete them easily using the File Explorer. Using this script still takes time, but at least it won’t freeze up your windows and it will finish eventually. After a day of running the script, the number of files remaining reduced to 1.3 million.
import os
import time
from datetime import datetime
def main():
path = r"C:\your\path"
day_limit = 7
delete_files_older_than(day_limit, path)
def delete_files_older_than(days, path):
delete_age_in_seconds = time.time() - (days * 24 * 60 * 60)
for entry in os.scandir(path):
full_path = os.path.join(path, entry.name)
stat = os.stat(full_path)
if (stat.st_mtime <= delete_age_in_seconds):
print(f"Removing {entry.name} from {datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d')}")
os.remove(full_path)
if __name__ == '__main__':
main()