Python查找文件夹下所有指定后缀名的文件路径

部署运行你感兴趣的模型镜像
# encoding: utf-8

'''
@file: readFilePath.py
@time: 2022/10/19
@author: zpj
'''

import os

# 查找指定文件夹下所有相同后缀名的文件
def search_sameSuffix_file(dirPath, suffix):
    dirs = os.listdir(dirPath)
    for currentFile in dirs:
        fullPath = dirPath + '/' + currentFile
        if os.path.isdir(fullPath):
            search_sameSuffix_file(fullPath, suffix)
        elif currentFile.split('.')[-1] == suffix:
            print(fullPath)
            # 保存获取到的文件路径写入txt
            f = open('filePath.txt', 'a+')
            f.write(fullPath + '\n')
            f.close()
            
if __name__ == "__main__":
    # 添加文件夹路径
    dirPath = ' '
    # 添加文件后缀名
    suffix = ' '
    search_sameSuffix_file(dirPath, suffix)

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

Python 中,有多种方法可以查找目录下指定后缀文件,以下是几种常见的实现方式: #### 使用 `os.listdir` 和递归 ```python import os def get_full_filelist(base_dir='.', target_ext='') -> list: fname_list = [] for fname in os.listdir(base_dir): path = os.path.join(base_dir, fname) if os.path.isfile(path): fname_main, fname_ext = os.path.splitext(fname) if fname_ext == target_ext or target_ext == '': fname_list.append(path) elif os.path.isdir(path): temp_list = get_full_filelist(path, target_ext) fname_list = fname_list + temp_list else: pass return fname_list ``` 此方法通过 `os.listdir` 遍历指定目录下的所有文件文件夹,对于文件夹会递归调用自身继续查找,最终返回符合后缀条件的文件路径名列表[^1]。 #### 使用 `os.walk` ```python import os def findAllFilesWithSpecifiedSuffix(target_dir, target_suffix="jp2"): find_res = [] target_suffix_dot = "." + target_suffix walk_generator = os.walk(target_dir) for root_path, dirs, files in walk_generator: if len(files) < 1: continue for file in files: file_name, suffix_name = os.path.splitext(file) if suffix_name == target_suffix_dot: find_res.append(os.path.join(root_path, file)) return find_res ``` 该方法使用 `os.walk` 函数遍历指定目录及其目录,通过 `os.path.splitext` 分离文件名和后缀名,将符合后缀条件的文件路径名添加到结果列表中[^4]。 #### 使用 `glob` ```python import glob def find_files_with_glob(path, target_ext): return glob.glob(f'{path}/**/*.{target_ext}', recursive=True) ``` `glob` 模块提供了一种简单的方式来查找符合特定模式的文件,`**` 表示递归匹配所有目录,`recursive=True` 开启递归查找功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值