所以我有一个文件夹,比如 D:\Tree,它只包含子文件夹(名称可能包含空格)。这些子文件夹包含一些文件 - 并且它们可能包含 "D:\Tree\SubfolderName\SubfolderName_One.txt"
和 "D:\Tree\SubfolderName\SubfolderName_Two.txt"形式的文件
(换句话说,子文件夹可能包含两者、一个或两者都不包含)。我需要找到子文件夹包含这两个文件的每次出现,并将它们的绝对路径发送到文本文件(采用以下示例中解释的格式)。考虑 D:\Tree 中的这三个子文件夹:
D:\Tree\Grass contains Grass_One.txt and Grass_Two.txt
D:\Tree\Leaf contains Leaf_One.txt
D:\Tree\Branch contains Branch_One.txt and Branch_Two.txt
考虑到这种结构和上面提到的问题,我希望能够在 myfile.txt 中编写以下几行:
D:\Tree\Grass\Grass_One.txt D:\Tree\Grass\Grass_Two.txt
D:\Tree\Branch\Branch_One.txt D:\Tree\Branch\Branch_Two.txt
如何做到这一点?预先感谢您的帮助!
注意:在 myfile.txt 中,“file_One.txt”位于“file_Two.txt”之前,这一点非常重要
最佳答案
import os
folderPath = r'Your Folder Path'
for (dirPath, allDirNames, allFileNames) in os.walk(folderPath):
for fileName in allFileNames:
if fileName.endswith("One.txt") or fileName.endswith("Two.txt") :
print (os.path.join(dirPath, fileName))
# Or do your task as writing in file as per your need
希望这有帮助......
关于python - 查找包含两个以特定字符串结尾的文件的所有子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618185/