2017-11-25 7 views
0

この関数はファイルパスを返しませんが、リストの追加を使用するとうまくいきます。 このコードを実行するとエラーが発生します。再帰からジェネレータを取得する方法

トレースバック(最後の最新の呼び出し): ファイル "C:/Users/admin/PycharmProjects/testProj/testFile.py"、行28、 で 印刷myFiles.next()を呼び出すとStopIteration

import os 

basePath1 = 'D:/my_backup/' 

def testFunction(basePath): 
    for each in os.listdir(basePath): 
     newBase = basePath 
     if os.path.isfile(newBase + each): 
      yield newBase + each 
     else: 
      newBase += each + '/' 
      testFunction(newBase) 


myFiles = testFunction(basePath1) 

print myFiles.next() 
print myFiles.next() 
print myFiles.next() 
+0

list.appendの使用方法を表示できますか? – TinyTheBrontosaurus

+0

また、そのフォルダには何がありますか? – TinyTheBrontosaurus

+0

インポートOS basePath1 = 'D:/ my_backup /' ます。myList =リスト() DEF testFunction(basePathを):os.listdirにおける各々について (basePathを): newBase = basePathを os.path.isfile IF( newBase +各): #降伏newBase +各 myList.append(newBase +各)他 : newBase + =各+ '/' testFunction(newBase) testFunction(basePath1) 印刷はmyList –

答えて

0

next()関数を使用して、イテレータのすべてのアイテムを手動で反復処理します。最後に到達し、返されるデータがなくなると、StopIterationが発生します。

したがって、この例外を回避するためにこれを試す必要があります。

for myFile in myFiles: 
    print myFile 
関連する問題