Python3避免在csv文件末尾引用和引用额外的行
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3避免在csv文件末尾引用和引用额外的行相关的知识,希望对你有一定的参考价值。
我正在尝试基于之前创建和连接的列表内容创建CSV文件。这笔交易是我的所有行记录在每行的开头和结尾都带有双引号。另外在文件的末尾,我得到了额外的白线。
码:
with open('/tmp/'+filename,"w", newline='') as output:
writer = csv.writer(output)
for item in update_records:
row = '{},{},{}'.format(item['field1'],item['field2'],item['field3'])
#print(row)
writer.writerow([row])
output.close()
当前输出:
我试过了:
writer = csv.writer(output, quotechar='', quoting=csv.QUOTE_MINIMAL)
但我得到的错误如下:
如果启用了引用,则必须设置quotechar
非常感谢你的支持。
答案
这里是一个使用DictWriter的答案,但是基于数据结构的一些猜测。有更简单的方法来编写它,例如你把它们作为词典列表。
import csv
update_records = [
{
"field1": "field1",
"field2": "en",
"field3": "field3"
},
{
"field1": "field1",
"field2": "de",
"field3": "field3"
}
]
filename = "test.csv"
with open('/tmp/'+filename,"w", newline='') as output:
# Define header, needed even if not written when using DictWriter
header = ["field1", "field2", "field3"]
writer = csv.DictWriter(output, fieldnames=header)
# Optional write the header
# writer.writeheader()
for item in update_records:
row = {}
# Only provide the fields 1 to 1 that are present in the header.
# There are plenty of cooler ways to do this, but hope this is clearer.
for head in header:
row[head] = item[head]
# print(row)
writer.writerow(row)
输出是这样的(/tmp/test.csv)(最后有一个空白行,但不知道如何将其显示为代码的一部分,因此添加了EOF):
field1,en,field3
field1,de,field3
EOF
另一答案
writerow应该将字段列表作为参数:
with open('/tmp/'+filename,"w", newline='') as output:
writer = csv.writer(output)
for item in update_records:
row = [item['field1'],item['field2'],item['field3']]
#print(row)
writer.writerow(row)
以上是关于Python3避免在csv文件末尾引用和引用额外的行的主要内容,如果未能解决你的问题,请参考以下文章