2016-07-19 153 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'),但我怀疑摆脱所有的开头和结尾的空白是更好的反正。