Python搜索指定后缀名的文件

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

运行结果部分截图如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值