python:programmes:find
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
python:programmes:find [2012/02/15 20:21] – créée root | python:programmes:find [2019/07/29 17:27] (Version actuelle) – [os.scandir] root | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
====== Chercher un fichier ou dossier ====== | ====== Chercher un fichier ou dossier ====== | ||
- | < | + | ===== os.walk ===== |
+ | |||
+ | < | ||
import os, fnmatch | import os, fnmatch | ||
Ligne 11: | Ligne 13: | ||
yield os.path.join(path, | yield os.path.join(path, | ||
</ | </ | ||
+ | |||
+ | |||
+ | ===== glob ===== | ||
+ | |||
+ | <code python> | ||
+ | >>> | ||
+ | >>> | ||
+ | [' | ||
+ | >>> | ||
+ | [' | ||
+ | </ | ||
+ | |||
+ | ===== os.scandir ===== | ||
+ | C'est la méthode la plus performante (des builtins modules) en rapidité et en souplesse de code: | ||
+ | |||
+ | Exemple pour trouver les fichiers **suid** d'un répertoire avec **crossmount** activé ou désactivé (option **xdev** de la commande **find**) : | ||
+ | <code python find.py> | ||
+ | def find(path, crossmount=True): | ||
+ | dev = os.stat(path).st_dev | ||
+ | try: | ||
+ | for entry in os.scandir(path): | ||
+ | if entry.is_dir() and not entry.is_symlink(): | ||
+ | if not crossmount and entry.stat().st_dev != dev: | ||
+ | continue | ||
+ | for result in find(entry.path, | ||
+ | yield result | ||
+ | yield entry | ||
+ | else: | ||
+ | yield entry | ||
+ | except OSError as e: | ||
+ | print(e, file=sys.stderr) | ||
+ | |||
+ | # Search suid files | ||
+ | for suid in (f.path for f in find('/ | ||
+ | print(suid) | ||
+ | </ | ||
+ | |||
+ | Recherche les fichiers qui ont un **// | ||
+ | < | ||
+ | $ ./find.py | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | </ | ||
+ | |||
+ | |||
+ | ===== os.listdir ===== | ||
+ | C'est la méthode la moins performante: | ||
+ | |||
+ | <code python> | ||
+ | def find_dirs(root_dir): | ||
+ | try: | ||
+ | for entry in os.listdir(root_dir): | ||
+ | entry_path = os.path.join(root_dir, | ||
+ | if os.path.isdir(entry_path) and not os.path.islink(entry_path): | ||
+ | for result in find_dirs(entry_path): | ||
+ | yield result | ||
+ | else: | ||
+ | yield entry_path | ||
+ | |||
+ | except OSError as e: | ||
+ | print(e, file=sys.stderr) | ||
+ | </ | ||
+ | |||
+ | ===== faster-than-walk ===== | ||
+ | C'est un module externe [[https:// |
python/programmes/find.1329337309.txt.gz · Dernière modification : 2012/02/15 20:21 de root