2017-08-10 72 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」 之前....

相關問題