2017-08-10 6 views
2

したがって、サブフォルダのみを含むD:\ Treeというフォルダがあります(名前にはスペースが含まれることがあります)。これらのサブフォルダにはいくつかのファイルが含まれており、"D:\Tree\SubfolderName\SubfolderName_One.txt""D:\Tree\SubfolderName\SubfolderName_Two.txt"の形式のファイルが含まれている場合があります(つまり、サブフォルダには両方、1つ、またはいずれも含まれていない可能性があります)。私は、サブフォルダにこれらのファイルの両方が含まれているすべての場所を見つけ、絶対パスをテキストファイルに送信する必要があります(次の例で説明する形式)。 Dにこれら三つのサブフォルダを考えてみましょう:\ツリー:特定の文字列で終わる2つのファイルを含むすべてのサブフォルダの検索

このような構造と上記の問題を考えると
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 

どうすればいいですか?助けをあらかじめありがとう!

注:それは

+0

「Dir D:\ Tree \ * _ One.txt/b/s> somefile.txt」と別のリスト「dir D:\ Tree \ *」を使用してリストを作成していたことが、 _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

が再帰的なソリューションです

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だと思います)。しかし、このスクリプトに2つの可能なエンディングがどのようなものかを教えてもらえますか? – Koloktos

+1

私は解決策を改良しました。今度は2つのエンディングを渡し、それらに合ったファイルをプリントします。 – Anonta

2
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 

・ホープ、このことができます....ここ

関連する問題