Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentes Révision précédente Prochaine révision | Révision précédente | ||
python:file_system [2021/09/19 18:49] marclebrun [Suppression de fichiers] |
python:file_system [2022/11/07 08:23] (Version actuelle) marclebrun [Date et heure d'un fichier] |
||
---|---|---|---|
Ligne 52: | Ligne 52: | ||
.... | .... | ||
</code> | </code> | ||
+ | |||
+ | ===== Date et heure d'un fichier ===== | ||
+ | |||
+ | Source: [[https://www.geeksforgeeks.org/how-to-get-file-creation-and-modification-date-or-time-in-python/]] | ||
+ | |||
+ | Renvoie une valeur float représentant le nombre de secondes | ||
+ | écoulées depuis l'origine (qui dépend du système, sous Unix c'est | ||
+ | le 1er janvier 1970) : | ||
+ | |||
+ | <code python> | ||
+ | import os | ||
+ | |||
+ | file_path = "c:\\chemin\\vers\\mon\\fichier" | ||
+ | time_created = os.path.getctime(file_path) | ||
+ | time_modified = os.path.getmtime(file_path) | ||
+ | </code> | ||
+ | |||
+ | Pour transformer ces valeurs en quelque chose de lisible, utiliser | ||
+ | les fonctions **time.ctime()** puis **time.strptime()** et **time.strftime()** : | ||
+ | |||
+ | <code python> | ||
+ | import os, time | ||
+ | |||
+ | time_modified = time.strptime(time.ctime(os.path.getmtime(file_path))) | ||
+ | print(time.strftime("%d/%m/%Y, %H:%M:%S", time_modified)) | ||
+ | print(time.strftime("%Y%m%d-%H%M%S", time_modified)) | ||
+ | </code> | ||
+ | |||
===== Découpage de chemin ===== | ===== Découpage de chemin ===== | ||
Ligne 100: | Ligne 128: | ||
for file in list_of_files: | for file in list_of_files: | ||
print(file, os.path.getctime(os.path.join(path, file))) | print(file, os.path.getctime(os.path.join(path, file))) | ||
+ | </code> | ||
+ | |||
+ | Filtrer selon une extension : | ||
+ | |||
+ | <code python> | ||
+ | for file in list_of_files: | ||
+ | if file.endswith(".txt"): | ||
+ | print(os.path.join(path, file)) | ||
</code> | </code> | ||
Ligne 111: | Ligne 147: | ||
path = './log' | path = './log' | ||
- | list_of_files = os.listdir(path) | + | file_names = os.listdir(path) |
- | full_path = [path+"/{0}".format(x) for x in list_of_files] | + | full_paths = [path+"/{0}".format(x) for x in file_names] |
+ | |||
+ | oldest_file = min(full_paths, key=os.path.getctime) | ||
- | if len(list_of_files) == 25: | + | os.remove(oldest_file) |
- | oldest_file = min(full_path, key=os.path.getctime) | + | |
- | os.remove(oldest_file) | + | |
</code> | </code> | ||