我有一些代码如下:
def read_lines(csv_reader, row_list):
for row_number, row in enumerate(csv_reader):
if row_number in row_list:
yield row_number, row
with open(file_name, 'r') as File:
reader = csv.reader(File, dialect='tab_delim')
r = list(range(4))
r2 = list(range(4, 7))
combined_list = []
combined_list2 = []
for row_number, row in read_lines(reader, r):
row_tuples = list(it.combinations(row, 2))
combined_list.append(row_tuples)
这对于在前三行中读取并生成所需的Combined_list效果很好。但是,当我稍后尝试使用以下代码在第二行(4,7)中读取时:
for row_number, row in read_lines(reader, r2):
row_tuples = list(it.combinations(row, 2))
combined_list.append(row_tuples)
未读入行,并且Combined_list2为空。我试图进行故障排除,但似乎无法弄清楚如何在不关闭文件然后重新打开的情况下使它工作(我试图避免这种情况)。
答案 0 :(得分:1)
您将重复使用已迭代的同一reader
对象,因此,第二次使用它调用read_lines
时,该对象将为空。
您需要重置或重新创建它-Reset the csv.reader() iterator
for row_number, row in read_lines(reader, r):
# do stuff
# TODO: reset 'reader'
for row_number, row in read_lines(reader, r2):
# do stuff
或者,将所有行读入一个生成器,然后在迭代一次时将其过滤掉
with open(file_name, 'r') as File:
reader = csv.reader(File, dialect='tab_delim')
r = list(range(4))
r2 = list(range(4, 7))
combined_list = []
combined_list2 = []
for row_number, row in enumerate(csv_reader):
data = list(it.combinations(row, 2))
if row_number in r:
combined_list.append(data)
if row_number in r2:
combined_list2.append(data)