[Python] Use python to traverse folders to find all files with the same name and all files with the same suffix in the specified folder

1. Folder structure

Prepare the following folder structure as a demonstration:

insert image description here

2. Find all files with the same name in the specified folder

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)
    

Results of the:

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

3. Find all files with the same suffix in the specified folder

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)
             

Results of the:

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

Note: When searching for files with the same suffix, the recursive call must be placed ifinside, but not inside elif, otherwise, an error will occur when the folder name is the same as the file suffix.
For example: to find txta file with a suffix, there is just another txtfolder, because the recursion is placed in elifit, then the traversal will stop at the txt folder instead of traversing txtthe contents of the folder.

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)
      

Results of the:

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 

It can be seen E:/Code/Python/txt that the expected result E:/Code/Python/txt/test.txtdoes not meet the

Guess you like

Origin blog.csdn.net/aidijava/article/details/125828429