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