Python CSV DictReader/Writer 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1202855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:42:25  来源:igfitidea点击:

Python CSV DictReader/Writer issues

pythoncsv

提问by saturdayplace

I'm trying to extract a bunch of lines from a CSV file and write them into another, but I'm having some problems.

我试图从一个 CSV 文件中提取一堆行并将它们写入另一个文件中,但我遇到了一些问题。

import csv

f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames

target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)

while True:
try:
    row = r.next()
    if r.line_num <= 2: #first two rows don't matter
        continue
    else:
        w.writerow(row)

except StopIteration:
    break

f.close()
target.close()

Running this, I get the following error:

运行这个,我收到以下错误:

Traceback (most recent call last):
File "unify.py", line 16, in <module>
    w.writerow(row)
File "C:\Program Files\Python25\lib\csv.py", line 12
    return self.writer.writerow(self._dict_to_list(row
File "C:\Program Files\Python25\lib\csv.py", line 12
    if k not in self.fieldnames:
TypeError: argument of type 'NoneType' is not iterable

Not entirely sure what I'm dong wrong.

不完全确定我错了什么。

回答by Daniel Roseman

I don't know either, but since all you're doing is copying lines from one file to another why are you bothering with the csvstuff at all? Why not something like:

我也不知道,但是既然您所做的只是将行从一个文件复制到另一个文件,那么您为什么还要为这些csv东西烦恼呢?为什么不是这样的:

f = open("my_csv_file.csv", "r")
target = open("united.csv", 'w')

f.readline()
f.readline()
for line in f:
    target.write(line)

回答by kynan

To clear up the confusion about the error: you get it because r.fieldnamesis only set once you read from the input file for the first time using r. Hence the way you wrote it, fieldnameswill always be initialized to None.

消除关于错误的困惑:你会得到它,因为r.fieldnames只有在你第一次使用r. 因此,您编写它的方式fieldnames将始终初始化为None.

You may initialize w = csv.DictWriter(united, fieldnames=fieldnames)with r.fieldnamesonly after you read the first line from r, which means you would have to restructure your code.

您可以初始化w = csv.DictWriter(united, fieldnames=fieldnames)r.fieldnames你读的第一行后,才r,你就必须这就意味着要重组你的代码。

This behavior is documented in the Python Standard Library documentation

此行为记录在Python 标准库文档中

DictReader objects have the following public attribute:

csvreader.fieldnames

If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.

DictReader 对象具有以下公共属性:

csvreader.fieldnames

如果在创建对象时未作为参数传递,则在第一次访问或从文件中读取第一条记录时初始化此属性。

回答by RyanW

As for the exception, looks like this line:

至于异常,看起来像这一行:

w = csv.DictWriter(united, fieldnames=fieldnames)

should be

应该

w = csv.DictWriter(target, fieldnames=fieldnames)

回答by Tim Keating

The reason you're getting the error is most likely that your original CSV file (my_csv_file.csv) doesn't have a header row. Therefore, when you construct the reader object, its fieldnames field is set to None.

您收到错误的原因很可能是您的原始 CSV 文件 (my_csv_file.csv) 没有标题行。因此,当您构造 reader 对象时,其 fieldnames 字段设置为None

When you try to write a row using the writer, it first checks to make sure there are no keys in the dict that are not in its list of known fields. Since fieldnamesis set to None, an attempt to dereference the key name throws an exception.

当您尝试使用 writer 写入一行时,它首先检查以确保 dict 中没有不在其已知字段列表中的键。由于fieldnames设置为None,尝试取消引用键名会引发异常。