简体   繁体   English

csv.reader / writer - 为什么迭代 CSV 对象会导致 writer 没有输出?

[英]csv.reader / writer - why does iterating CSV object result in no output from writer?

I found this example of a simple CSV read / write .我找到了这个简单的 CSV 读/写示例

This code reads and writes the CSV file, sorting on the 7th column.此代码读取和写入 CSV 文件,按第 7 列排序。

import csv
with open('input.csv', newline='') as csvfile:
    rdr = csv.reader(csvfile)
    l = sorted(rdr, key=lambda x: x[6], reverse=True)
with open('output.csv', 'w') as csvout:
    wrtr = csv.writer(csvout)
    wrtr.writerows(l)

The code above outputs a CSV file into output.csv上面的代码将一个 CSV 文件输出到 output.csv

If I need to do some additional processing other than sorting, I might do it by iterating through the rows of the CSV object.如果我需要进行排序以外的其他处理,我可能会通过遍历 CSV 对象的行来完成。 The simplest example exhibiting the problem is just iterating the rows and printing them:展示问题的最简单示例就是迭代行并打印它们:

import csv
with open('input.csv', newline='') as csvfile:
    rdr = csv.reader(csvfile)
    for arow in rdr:
        print(arow)
    l = sorted(rdr, key=lambda x: x[6], reverse=True)
with open('output.csv', 'w') as csvout:
    wrtr = csv.writer(csvout)
    wrtr.writerows(l)

The code above prints the CSV rows to the screen as expected.上面的代码按预期将 CSV 行打印到屏幕上。 However, the output.csv file is then empty ( 0 bytes)但是, output.csv 文件然后是空的( 0 字节)

Why does iteration through the rows cause no output from csv.writer?为什么遍历行会导致 csv.writer 没有输出? Is there some type of persistent state in the CSV object that has to be reset? CSV 对象中是否存在某种类型的持久状态需要重置?

As @Barmar correctly noted:正如@Barmar 正确指出的那样:

rdr is an iterator. rdr 是一个迭代器。 You can only loop through an iterator once.一个迭代器只能循环一次。 Convert it to a list if you want to process it multiple times.如果您想多次处理它,请将其转换为列表。

Working code:工作代码:

import csv
with open('input.csv', newline='') as csvfile:
    rdr = csv.reader(csvfile)
    mylist = list(rdr)
    for arow in mylist:
        print(arow)
    l = sorted(mylist, key=lambda x: x[6], reverse=True)
with open('output.csv', 'w') as csvout:
    wrtr = csv.writer(csvout)
    wrtr.writerows(l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM