Skip to content

Instantly share code, notes, and snippets.

@anderssonfilip
Last active February 15, 2022 07:05
Show Gist options
  • Save anderssonfilip/8955589 to your computer and use it in GitHub Desktop.
Save anderssonfilip/8955589 to your computer and use it in GitHub Desktop.
Simple Python script to archive older files in a folder by tagging
import os
import glob
from datetime import date, timedelta
import re
from time import gmtime, strftime
folder = '<Insert folder name here>'
files = ['FileA.txt', 'FileB.txt']
archivePeriod = 5 # archive period in days
for file in files :
try :
# Remove file if older than archive period
[fn, ff] = file.split('.') # filename, fileformat
for archivedFile in glob.glob(fn + "*" + ff): # Find archived files
matches = re.search(('(?<={}_)\d+(?=.txt)').format(fn), archivedFile)
if matches:
if matches.group(0) < strftime('%Y%m%d' ,(date.today()-timedelta(days=archivePeriod)).timetuple()):
os.remove(os.path.join(dir, archivedFile))
# Rename the file by appending last modified time stamp to the file name
path = folder + file
os.rename(path, path.replace('.txt', '_' + strftime('%Y%m%d', gmtime(os.path.getmtime(path))) + '.txt'))
except FileNotFoundError :
print ('File ' + path + ' was not found')
except FileExistsError:
print ('File ' + path.replace('.txt', '_' + strftime('%Y%m%d', gmtime(os.path.getmtime(path))) + '.txt') + ' already exists')
@lraman-collab
Copy link

thanks

@GodwinAhmed
Copy link

Really helped , thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment