【问题标题】:For loop terminates after first item in pythonfor循环在python中的第一项后终止
【发布时间】:2019-11-18 18:54:08
【问题描述】:

我正在尝试通过提供 with 语句和列出我要处理的文件的文件路径的文本文件来处理目录中的多个图像(处理包括显示的灰度以及一些去噪和像素强度测量)。 使用下面显示的代码,程序正确处理列表中的第一个文件,然后在处理其他文件之前结束。有谁知道为什么以及如何让它遍历列出的所有文件?

#establish loop
with open('file_list.txt') as inf:
    for line in inf:
       path = line

# grayscale and plot
original = io.imread(path, plugin = 'pil')
grayscale = rgb2gray(original)

【问题讨论】:

标签: python for-loop directory iterator with-statement


【解决方案1】:

每次迭代都会给出一个新的path,所以你会得到最后一条路径,而不是第一条。分配路径后,在循环内运行imreadrgb2gray

#establish loop is correct
with open('file_list.txt') as inf:
    for line in inf:
       path = line # Each iteration path will have a new path value

       # grayscale and plot
       original = io.imread(path, plugin = 'pil')
       grayscale = rgb2gray(original)

【讨论】:

    猜你喜欢
    • 2018-06-10
    • 1970-01-01
    • 2010-11-02
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多