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

导读:本篇文章讲解 【Python】使用python遍历文件夹,实现查找指定文件夹下所有相同名称的文件、所有相同后缀名的文件,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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不符合

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84886.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!