LoginSignup
7
12

More than 5 years have passed since last update.

Pythonでlinuxのfindのようなファイル検索

Last updated at Posted at 2017-05-03

いつも忘れるので,メモ.

myfind.py
import os
import fnmatch
import argparse

# parsing arguments
parser = argparse.ArgumentParser()
parser.add_argument('path', type=str, default=None,
    help="Directory for searching files.")
parser.add_argument('-n', '--name', type=str, default='*',
    help="Pattern for searching files.")
args = parser.parse_args()

# search
files = list()
for root, dirs, names in os.walk(args.path):
    new_files = [ os.path.join(root, f) for f in names
        if fnmatch.fnmatch(os.path.join(root, f), args.name) ]
    files.extend(new_files)

# print
for f in files:
    print f
# ls -F .
hoge/   uga/    ponyo.txt
# ls -F hoge
hogera.py   honyara.sh
# ls -F uga
uga.sh      ugera.py
# python myfind.py . --name "*.py"
./hoge/hogera.py
./uga/ugera.py
7
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
12