python:programmes:find
Ceci est une ancienne révision du document !
Table des matières
Chercher un fichier ou dossier
os.walk
import os, fnmatch def locate(pattern, root=os.curdir): '''Locate all files matching supplied filename pattern in and below supplied root directory.''' for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename)
glob
>>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif']
os.scandir
C'est la méthode la plus performante en rapidité et en souplesse de code:
- find.py
def find(root): try: for entry in os.scandir(root): if entry.is_dir() and not entry.is_symlink(): for result in find2(entry.path): yield result yield entry else: yield entry except OSError as e: print(e, file=sys.stderr) { print(f.path) for f in find('/home/gigix') if f.is_file() and f.stat().st_mode & stat.S_ISUID }
Recherche les fichiers qui ont un setuid de positionné:
$ ./find.py /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/lib/dbus-1.0/dbus-daemon-launch-helper /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/lib/polkit-1/polkit-agent-helper-1 /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/mount /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/pkexec /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/chfn /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/ksu /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/umount /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/su /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/chsh /home/gigix/Documents/VSCode-Anywhere/Third-Party/Junest/chroot/usr/bin/newgrp
os.scandir
C'est la méthode la moins performante:
def find_dirs(root_dir): try: for entry in os.listdir(root_dir): entry_path = os.path.join(root_dir, entry) 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)
python/programmes/find.1564334650.txt.gz · Dernière modification : 2019/07/28 17:24 de root