2017-08-10 66 views
2

因此,我有一个文件夹,例如D:\ Tree,它只包含子文件夹(名称可能包含空格)。这些子文件夹包含几个文件 - 并且它们可能包含"D:\Tree\SubfolderName\SubfolderName_One.txt""D:\Tree\SubfolderName\SubfolderName_Two.txt"(换句话说,子文件夹可能包含它们两个,一个或两者都不包含)的文件。我需要找到每个子文件夹都包含这两个文件的每一次出现,并将它们的绝对路径发送到一个文本文件(采用以下示例中说明的格式)。考虑d这三个子文件夹:\树:查找包含以特定字符串结尾的两个文件的所有子文件夹

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

+0

一件事_Two.txt/b/s> somefile2.txt“使用CMD,但我不知道该怎么办。 – Koloktos

+0

由于问题标有“python”,请添加您的代码以查看问题出在哪里。 – andpei

+2

我的建议是看看[os.walk](https://docs.python.org/3.5/library/os.html#os.walk),尝试一下,然后问一个更具体的问题,如果你得到卡住。人们需要知道你实际做了什么,为什么它失败了,而不是你所考虑的。 –

回答

1

这里是一个递归解决方案另一份“目录d:\树\ *:我已经考虑过使用被列了清单 “\树\ * _此时就把one.txt存盘/ b/S> somefile.txt目录d”

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') 
+0

原谅我的不足之处,但究竟是什么后缀,以及如何在这种情况下定义它?看看这个逻辑,它似乎是我正在寻找的文件的末尾(我猜_One.txt),但是我怎么告诉这个脚本这两个可能的结局是什么? – Koloktos

+1

我改进了解决方案,现在它传递两个结尾并打印与之匹配的文件 – Anonta

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 

希望这有助于谈到 “file_Two.txt” 之前....

相关问题