LoginSignup
0
0

More than 3 years have passed since last update.

指定したディレクトリ内を再帰的に探索してファイルを見る

Last updated at Posted at 2020-10-29

os.walk() を使って実装

import argparse
import os


def find_all_files(directory):
    for root, dirs, files in os.walk(directory):
        yield root
        for file in files:
            yield os.path.join(root, file)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "directory", type=str, help="directory that you hope to look into."
    )
    parser.add_argument(
        "-e", "--extension", type=str, help="specify files with extension"
    )
    parser.add_argument("-c", "--cat", help="cat the file", action="store_true")
    parser.add_argument("-w", "--wc", help="wc the file", action="store_true")
    args = parser.parse_args()

    for file in find_all_files(args.directory):
        if args.extension:
            extension = file.split(".")[-1]
            if extension != args.extension:
                continue

        if args.wc:
            os.system("wc " + file)
        else:
            print(file)

        if args.cat:
            print("##### HEAD OF THE FILE #####\n\n")
            for line in open(file):
                print(line, end="")
            print("##### END OF THE FILE #####\n\n")


if __name__ == "__main__":
    main()

使い方

$ python find_all_files.py --help
usage: find_all_files.py [-h] [-e EXTENSION] [-c] [-w] directory

positional arguments:
  directory             directory that you hope to look into.

optional arguments:
  -h, --help            show this help message and exit
  -e EXTENSION, --extension EXTENSION
                        specify files with extension
  -c, --cat             cat the file
  -w, --wc              wc the file

次のようにすると、指定したディレクトリ内の .py ファイルを再帰的に探索して全部中身が見れます。

python find_all_files.py directory -e py -c

参考にしたサイト

0
0
0

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
0
0