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/03 06:10] marclebrun [Script en cours] |
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 85: | Ligne 113: | ||
os.makedirs("/home/marc/nouveau/dossier", mode=0o755, exist_ok=True) | os.makedirs("/home/marc/nouveau/dossier", mode=0o755, exist_ok=True) | ||
+ | </code> | ||
+ | |||
+ | ===== Lister les fichiers d'un dossier ===== | ||
+ | |||
+ | Lister les fichiers d'un dossier avec leur date/heure : | ||
+ | |||
+ | <code python> | ||
+ | import os | ||
+ | |||
+ | path = './data' | ||
+ | |||
+ | list_of_files = os.listdir(path) | ||
+ | | ||
+ | for file in list_of_files: | ||
+ | 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> | ||
+ | |||
+ | ===== Suppression de fichiers ===== | ||
+ | |||
+ | Supprimer le plus vieux fichier d'un dossier | ||
+ | |||
+ | <code python> | ||
+ | import os | ||
+ | |||
+ | path = './log' | ||
+ | |||
+ | file_names = os.listdir(path) | ||
+ | full_paths = [path+"/{0}".format(x) for x in file_names] | ||
+ | |||
+ | oldest_file = min(full_paths, key=os.path.getctime) | ||
+ | |||
+ | os.remove(oldest_file) | ||
</code> | </code> | ||