2017-07-05 10 views
0

私はdictionaryを持っていて、その中にファイル/ディレクトリパスがあります。 forループでは、パスがファイルまたはディレクトリにリンクしているかどうかを確認します。それがディレクトリの場合は、ループをもう一度行う必要がありますが、レベルは1つ深くなります。進行中のForループ - Python

私はもはやdictのパスがなくなるまでこれを行う必要があります。 dirにはいくつのレベルがあり、その中に冗長なコードを作成したくないのか分かりません。

誰かが私を助けることができますか?

例:

# here i do have the top level for loop 
for each_path in file_or_dir_paths.keys(): 
    # then i check if the path links to a dir 
    # in dictionary[each_path] the date of the file/dir is stored 
    # but this isnt important yet 
    status = is_it_dir(each_path, dictionary[each_path]) 
    # status 0 means an empty dir 
    if status == 0: 
     del dictionary[each_path] 
    # status 1 means a dir with files in it 
    if status == 1: 
     # and here i do have to do the loop again 
     # which is redundant and will get deeper with every loop iteration 
     dictionary[each_path] = for_loop_again 
    # status 10 means path is a file 
    if status == 10: 
     # this section is not important right now 
     dictionary[each_path] = True 

答えて

1

ディレクトリ構造を横断する、Pythonのbuildin機能walk()を使う方が良いでしょう。 walk()は、どの深さでもすべてのサブディレクトリを訪問します。使用方法は次のとおりです。あなたには、いくつかの理由のために、独自のトラバーサルのコードを書きたい場合は

from os import walk 

# assume variable root contain your root path 

for path, dirs, files in walk(root): 
    # do what you need to do with the files and dirs 

、あなたは(あなたが示唆するように見えるよう)あなたがネストされたループの一定量を持つことができない、再帰を使用する必要があります