Python不会将多个列表中的所有数据写入csv文件

2024-05-15 17:11:13 发布

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

我正在抓取一个XML文件并将数据存储到多个列表中。最后,我从列表中获取数据并将其写入CSV文件。代码运行时没有任何错误,但是当我在之后检查数据时,似乎最后列表中的项没有写入文件。最终文件中应该有大约2000行。在

我的代码是:

with codecs.open("some_file.csv", 'w', encoding='utf-8') as file:
    writer = csv.writer(file, lineterminator='\n', delimiter=";")

    for a, b, c in zip(l1, l2, l3):
        writer.writerow([a, b, c])

我忘记了this主题,但我已经使用了with。我错过了什么?在


Tags: 文件csv数据代码列表错误withxml
2条回答

代码看起来很好

$ cat test.py
import codecs
import csv

l1 = ['hest', 'hat', 'test', 'more test']
l2 = ['hest2', 'hat', 'test', 'even more test']
l3 = ['hest3', 'hat', 'test', 'even even more test']

with codecs.open("some_file.csv", 'w', encoding='utf-8') as file:
    writer = csv.writer(file, lineterminator='\n', delimiter=";")

    for a, b, c in zip(l1, l2, l3):
    writer.writerow([a, b, c])

$ python test.py
$ cat some_file.csv 
hest;hest2;hest3
hat;hat;hat
test;test;test
more test;even more test;even even more test

我想你可能想看看你的三个清单,然后在zip。在

如果列表的长度不一样,那么zip会将有问题的列表抛出。在

#!/usr/bin/env python

import csv
import codecs

L1 = ["foo", "bar", "bat", "baz"] # <  this guy has one more! expect to be truncated
L2 = ["hoo", "hah", "hee"] # < note, one field less!
L3 = range(2) #< note, only two fields long! expect entire line to be dropped!

with codecs.open("test.csv", "w", encoding="utf-8") as f:
    writer = csv.writer(f, lineterminator="\n", delimiter=";")
    for row in zip(L1, L2, L3):
        writer.writerow(row)

因为在L3中只有两个值,其余值有三个,zip将截断错误输出。在

^{pr2}$

当然,您会注意到,我使用zip为三个列表中的每个索引提供一个列表值。这与你的例子不同。我不知道你到底在做什么,但是如果这些“l”值代表一个列表,那么就没有必要显式地创建这些值,然后再将它们添加到列表中。在

同样,如果可能的话,最好能看到一个输入的例子。在构建这些列表时,可能需要插入None值(或空字符串,或其他任何东西)以使它们“匹配”。在

L1 = ["foo", "bar", "bat", "baz"]
L2 = ["hoo", "hah", "hee", None]
L3 = range(2) + [None, None]

这可能会给你想要的:

~$ cat test.csv
foo;hoo;0
bar;hah;1
bat;hee;
baz;;

相关问题 更多 >