Article directory
1. Folder structure
Prepare the following folder structure as a demonstration:
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
if
inside, but not insideelif
, otherwise, an error will occur when the folder name is the same as the file suffix.
For example: to findtxt
a file with a suffix, there is just anothertxt
folder, because the recursion is placed inelif
it, then the traversal will stop at the txt folder instead of traversingtxt
the 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 resultE:/Code/Python/txt/test.txt
does not meet the