Python CSV DictReader/Writer问题

2024-05-12 14:21:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从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()

运行此命令时,出现以下错误:

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

不完全确定我做错了什么。


Tags: 文件csvinpyselftargetcloseif
3条回答

至于例外情况,如下所示:

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

应该是

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

要清除关于错误的混淆:您得到它是因为r.fieldnames只在第一次使用r从输入文件读取时设置。因此,您编写它的方式,fieldnames将始终初始化为None

只有在从r中读取第一行之后,才能使用r.fieldnames初始化w = csv.DictWriter(united, fieldnames=fieldnames),这意味着您必须重新构造代码。

此行为记录在Python Standard Library documentation

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.

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

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

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

相关问题 更多 >