Projet

Général

Profil

« Précédent | Suivant » 

Révision 6f6221a2

Ajouté par Mikaël Ates il y a plus de 9 ans

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

Voir les différences:

calebasse/utils.py
1
import os
2

  
1 3
from django.contrib.auth.models import Group
2 4
from django.conf import settings
3 5

  
......
90 92
    if not hasattr(settings, 'SERVICE_SETTINGS'):
91 93
        return None
92 94
    return settings.SERVICE_SETTINGS.get(service, {}).get(setting_name) or default_value
95

  
96
def get_last_file(path, prefix=None, suffix=None):
97
    '''
98
    A filename is of format year-mont-day-hour-min-sec.xml or
99
    prefix_year-mont-day-hour-min-secsuffix
100

  
101
    If suffix is None, only file *_year-mont-day-hour-min-sec are treated.
102
    If prefix is None, all files *_year-mont-day-hour-min-secsuffix are
103
    treated.
104
    '''
105
    if not path or not os.path.isdir(path):
106
        return None
107
    cv_files = [(f, f) for f in os.listdir(path) \
108
            if os.path.isfile(os.path.join(path, f)) ]
109
    if prefix:
110
        cv_files = [(f1, f2[len(prefix) + 1:])
111
                for f1, f2 in cv_files if f2.startswith(prefix)]
112
    else:
113
        cv_files = [(f1, f2.rsplit('_', 1)[-1])
114
                for f1, f2 in cv_files]
115
    if suffix:
116
        cv_files = [(f1, f2[:-len(suffix)])
117
                for f1, f2 in cv_files if f2.endswith(suffix)]
118
    fmt = '%Y-%d-%m-%H-%M-%S'
119
    cv_files_and_dates = list()
120
    for f1, f2 in cv_files:
121
        try:
122
            d = datetime.strptime(f2, fmt)
123
        except:
124
            pass
125
        else:
126
            cv_files_and_dates.append((f1, d))
127
    if len(cv_files_and_dates):
128
        cv_files_and_dates = sorted(cv_files_and_dates,
129
                key=lambda x:x[1], reverse=True)
130
        return os.path.join(path, cv_files_and_dates[0][0])
131
    else:
132
        return None

Formats disponibles : Unified diff