1.问题背景
需要搜索指定文件夹下某些特定后缀的文件,然后输出这些文件的绝对路径,作为后续工作的输入。
2.Python脚本
先直接上脚本,大家可以直接复制保存到本地用。
# -*- coding: UTF-8 -*-
import os
import argparse
def search_file(dir_path, filters) :
print("search files begin in dir {}".format(dir_path))
with open("lib_file.txt", 'a') as f:
for cur_dir, sub_dir, files in os.walk(dir_path) :
for file in files :
if os.path.splitext(file)[1] in filters :
file_abs_path = os.path.join(cur_dir, file)
print(file_abs_path)
f.write(file_abs_path + '\n')
print("search end.")
if __name__ == '__main__' :
# search_file("c:\\Users\\", ['.aar' , '.jar'])
parser = argparse.ArgumentParser(prog = 'search_file', description = "search files with some postfix in one dir")
parser.add_argument('-d', dest = 'dir', type = str, action = 'store', default = './',
help = 'the root dir that your want to search')
parser.add_argument('-f', dest = 'filters', action = 'store', nargs = '*', required = True,
help = 'the file that your want to filter,for example: .txt .jpg .py and so on')
args = parser.parse_args()
if args.dir and args.filters :
search_file(args.dir, args.filters)
3.使用方法
查看脚本帮助文档
D:\WorkSpace\search_file>python3 search_file.py -h
usage: search_file [-h] [-d DIR] [-f [FILTERS [FILTERS ...]]]
search files with some postfix in one dir
optional arguments:
-h, --help show this help message and exit
-d DIR the root dir that your want to search, default value
is script dir
-f [FILTERS [FILTERS ...]]
the file that your want to filter,for example: .txt
.jpg .py and so on
例如,查找C盘根目录下后缀为.txt、.jar后缀的文件,结果在终端中显示,并且把结果保存在脚本所在目录的文件中。
python3 search_file.py -d c:\ -f .txt .jar .py
运行结果部分截图如下: