首页 > 解决方案 > For loop terminates after first item in python

问题描述

I am trying to process multiple images in a directory by providing a with statement and a text file listing the file paths for the files I want processed (processing includes grayscaling shown and some de-noising and pixel intensity measures). With the code shown below the program correctly processes the first file on the list but then ends before processing the other files. Does anyone know why and how I can make it iterate through all files listed?

#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)

标签: pythonfor-loopdirectoryiteratorwith-statement

解决方案


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

#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)

推荐阅读