Add helper function to get the most recent file using the date in its name.

This commit is contained in:
Mikaël Ates 2015-01-13 16:12:12 +01:00
parent 6452a96921
commit 6f6221a2cd
1 changed files with 40 additions and 0 deletions

View File

@ -1,3 +1,5 @@
import os
from django.contrib.auth.models import Group
from django.conf import settings
@ -90,3 +92,41 @@ def get_service_setting(setting_name, default_value=None):
if not hasattr(settings, 'SERVICE_SETTINGS'):
return None
return settings.SERVICE_SETTINGS.get(service, {}).get(setting_name) or default_value
def get_last_file(path, prefix=None, suffix=None):
'''
A filename is of format year-mont-day-hour-min-sec.xml or
prefix_year-mont-day-hour-min-secsuffix
If suffix is None, only file *_year-mont-day-hour-min-sec are treated.
If prefix is None, all files *_year-mont-day-hour-min-secsuffix are
treated.
'''
if not path or not os.path.isdir(path):
return None
cv_files = [(f, f) for f in os.listdir(path) \
if os.path.isfile(os.path.join(path, f)) ]
if prefix:
cv_files = [(f1, f2[len(prefix) + 1:])
for f1, f2 in cv_files if f2.startswith(prefix)]
else:
cv_files = [(f1, f2.rsplit('_', 1)[-1])
for f1, f2 in cv_files]
if suffix:
cv_files = [(f1, f2[:-len(suffix)])
for f1, f2 in cv_files if f2.endswith(suffix)]
fmt = '%Y-%d-%m-%H-%M-%S'
cv_files_and_dates = list()
for f1, f2 in cv_files:
try:
d = datetime.strptime(f2, fmt)
except:
pass
else:
cv_files_and_dates.append((f1, d))
if len(cv_files_and_dates):
cv_files_and_dates = sorted(cv_files_and_dates,
key=lambda x:x[1], reverse=True)
return os.path.join(path, cv_files_and_dates[0][0])
else:
return None