Python3避免在csv文件末尾引用和引用额外的行

时间:2018-06-07 15:45:29

标签: python python-3.x 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()

当前输出:

enter image description here

我尝试过:

writer = csv.writer(output, quotechar='', quoting=csv.QUOTE_MINIMAL)

但我收到的错误如下:

  如果启用了引用,则必须设置

quotechar

非常感谢你的支持。

2 个答案:

答案 0 :(得分:2)

这是一个使用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

答案 1 :(得分:1)

写作者应该将字段列表作为参数:

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)