2016-07-19 150 views
0

我目前正在研究一些代碼,它將從.ini文件中查看多個目錄,然後將其打印並複製到新目錄中。我遇到了一個問題,即打印文件的for循環只能執行一次,因爲它應該執行5次。我如何解決這個問題,讓for循環在每次調用時都能正常工作?Python for循環僅執行一次

代碼:

def copyFiles(path): 
    rootPath = path 
    print(rootPath) 
    pattern = "*.wav" 
    search = "" 

    #searches the directories for the specified file type then prints the name 
    for root, dirs, files in os.walk(rootPath): 
     for filename in fnmatch.filter(files, pattern): 
      print(filename) 

def main(): 
    #opens the file containing all the directories 
    in_file = open('wheretolook.ini', "r") 

    #create the new directory all the files will be moved to 
    createDirectory() 

    #takes the path names one at a time and then passes them to copyFiles 
    for pathName in in_file: 
     copyFiles(pathName) 

Output i get from running my code

輸出應該有充分的diretory下0至4個文件。

謝謝你的幫助!

+1

請問您是否修復了您發佈的示例的代碼縮進,並且可能添加了目錄的「樹」(刪節版) – Sergey

+0

瘋狂猜測:'.ini'文件是否來自Windows並且正在運行某種的Unix? – cdarke

+0

請使用['with'](http://stackoverflow.com/q/3012488/1394393)打開(和關閉)文件。另外,如果你的文件每行只有一個路徑,'ini'是一個不恰當的擴展名。 ['ini'](https://en.wikipedia.org/wiki/INI_file)具有特定的格式。 (沒有特定的標準被完全採用,但所有通用的實現至少使用'[sections]'和'name = value'對。) – jpmc26

回答

0

迭代文件時得到的pathName在每行最後都有一個換行符。這就是爲什麼在每個路徑被打印後,你的輸出中會出現空行。

你需要調用你的路strip刪除換行符:

for pathName in in_file: 
    copyFiles(pathname.strip()) 

你可能更嚴格且使用rstrip('\n'),但我懷疑擺脫所有的開頭和結尾的空白是更好的反正。