Implementiert mit 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()
Wie benutzt man
$ 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
Sie können rekursiv nach .py-Dateien im angegebenen Verzeichnis suchen, um deren gesamten Inhalt anzuzeigen, indem Sie folgende Schritte ausführen:
python find_all_files.py directory -e py -c
Referenzierte Site
https://qiita.com/suin/items/cdef17e447ceeff6e79d