【Python】使用python遍历文件夹,实现查找指定文件夹下所有相同名称的文件、所有相同后缀名的文件

1. 文件夹结构

准备如下文件夹结构作为演示:

在这里插入图片描述

2. 查找指定文件夹下所有相同名称的文件

import os

# 查找指定文件夹下所有相同名称的文件
def search_file(dirPath, fileName):
    dirs = os.listdir(dirPath) # 查找该层文件夹下所有的文件及文件夹,返回列表
    for currentFile in dirs:
        fullPath = dirPath + '/' + currentFile 
        if os.path.isdir(fullPath): # 如果是目录则递归,继续查找该目录下的文件
            search_file(fullPath, fileName)
        elif currentFile == fileName:
            print(fullPath) 

if __name__ == "__main__":
    dirPath = 'E:/Code/Python' 
    fileName = 'test.txt'
    search_file(dirPath, fileName)
    

执行结果:

E:/Code/Python/a/test.txt
E:/Code/Python/b/test.txt
E:/Code/Python/txt/test.txt

3. 查找指定文件夹下所有相同后缀名的文件

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)

if __name__ == "__main__":
    dirPath = 'E:/Code/Python'
    suffix = 'txt'
    search_sameSuffix_file(dirPath, suffix)
             

执行结果:

E:/Code/Python/a/a.txt
E:/Code/Python/a/test.txt  
E:/Code/Python/b/b.txt     
E:/Code/Python/b/test.txt  
E:/Code/Python/txt/test.txt

注意:查找相同后缀名的文件时,递归调用必须放在if里,而不能放在elif里,否则当文件夹名称与文件后缀名相同时,会出错。
例如:查找txt后缀的文件,刚好又有一个txt的文件夹,因为递归放在了elif里,那么遍历会停在txt文件夹,而不去遍历txt文件夹里的内容。

import os

# 查找指定文件夹下所有相同后缀名的文件
def search_sameSuffix_file(dirPath, suffix):
    dirs = os.listdir(dirPath)
    for currentFile in dirs:
        fullPath = dirPath + '/' + currentFile
        if currentFile.split('.')[-1] == suffix: 
            print(fullPath)
        elif os.path.isdir(fullPath): # 递归判断放在elif里
            search_sameSuffix_file(fullPath, suffix)

if __name__ == "__main__":
    dirPath = 'E:/Code/Python'
    suffix = 'txt'
    search_sameSuffix_file(dirPath, suffix)
      

执行结果:

E:/Code/Python/a/a.txt
E:/Code/Python/a/test.txt
E:/Code/Python/b/b.txt   
E:/Code/Python/b/test.txt
E:/Code/Python/txt 

可以看到,E:/Code/Python/txt 与预期结果E:/Code/Python/txt/test.txt不符合

猜你喜欢

转载自blog.csdn.net/aidijava/article/details/125828429