所以我有一个文件夹,比如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
怎么可能这样做?在此先感谢您的帮助!
注意:“file_One.txt”位于myfile.txt中的“file_Two.txt”之前非常重要
答案 0 :(得分:2)
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
希望这会有所帮助......
答案 1 :(得分:1)
这是一个递归解决方案
def findFiles(writable, current_path, ending1, ending2):
'''
:param writable: file to write output to
:param current_path: current path of recursive traversal of sub folders
:param postfix: the postfix which needs to match before
:return: None
'''
# check if current path is a folder or not
try:
flist = os.listdir(current_path)
except NotADirectoryError:
return
# stores files which match given endings
ending1_files = []
ending2_files = []
for dirname in flist:
if dirname.endswith(ending1):
ending1_files.append(dirname)
elif dirname.endswith(ending2):
ending2_files.append(dirname)
findFiles(writable, current_path+ '/' + dirname, ending1, ending2)
# see if exactly 2 files have matching the endings
if len(ending1_files) == 1 and len(ending2_files) == 1:
writable.write(current_path+ '/'+ ending1_files[0] + ' ')
writable.write(current_path + '/'+ ending2_files[0] + '\n')
findFiles(sys.stdout, 'G:/testf', 'one.txt', 'two.txt')