Last active
February 15, 2022 07:05
-
-
Save anderssonfilip/8955589 to your computer and use it in GitHub Desktop.
Simple Python script to archive older files in a folder by tagging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks