【问题标题】:Python for loop only executes oncePython for 循环只执行一次
【发布时间】:2016-11-22 23:55:09
【问题描述】:

我目前正在编写一些代码,这些代码将从 .ini 文件中查看多个目录,然后打印并将它们复制到新目录。我遇到了一个问题,即打印文件的 for 循环在应该执行 5 次时只执行一次。我该如何修复它,以便每次调用 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

输出应该在每个目录下都有 0 到 4 个文件。

感谢您的帮助!

【问题讨论】:

  • 能否请您修复您发布的示例的代码缩进并添加目录的“树”(精简版)
  • 大胆猜测:.ini 文件是否来自 Windows,您是否在某种 Unix 上运行?
  • 请使用with 打开(和关闭)文件。此外,如果您的文件每行只有一个路径,ini 是不合适的扩展名。 ini 具有特定格式。 (没有完全采用特定标准,但所有常见实现都至少使用[sections]name=value 对。)

标签: python for-loop


【解决方案1】:

迭代文件时得到的pathName 在每一行的末尾都有一个换行符,但最后一行除外。这就是打印每个路径后在输出中出现空白行的原因。

您需要在路径上调用 strip 以删除换行符:

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

您可以更严格地使用rstrip('\n'),但我怀疑摆脱所有前导和尾随空格会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2019-06-20
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多