简体   繁体   English

Python3避免在csv文件末尾加引号和多余的行

[英]Python3 avoid quoting and extra lines at the end of the csv file

I am trying to create a CSV file based on a list content created and concatenated previously. 我试图根据先前创建和连接的列表内容创建CSV文件。 The deal is that all my lines records are coming with double quotes the beginning and at the end of every line. 关键是我的所有行记录都在每行的开头和结尾都用双引号引起来。 In addition at the end of the file, I am getting an extra white line. 另外,在文件末尾,我得到了一条额外的白线。

Code: 码:

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()

Current output: 电流输出:

在此处输入图片说明

I have tried: 我努力了:

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

But I am getting errors like: 但是我收到如下错误:

quotechar must be set if quoting enabled 如果启用了报价,则必须设置quotechar

thanks so much for the support. 非常感谢您的支持。

Here an answer using DictWriter instead, but an amount of guesswork based on the structure of data. 这里是使用DictWriter的答案,但是基于数据结构的大量猜测工作。 There are even easier ways to write it, eg you have them as a list of dictionaries. 甚至有更简单的编写方法,例如,将它们作为字典列表。

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)

Output is as such (/tmp/test.csv) (there is a blank line at the end, however no idea how to show this as part of the code so added EOF): 输出是这样的(/tmp/test.csv)(末尾有一个空行,但是不知道如何将其显示为代码的一部分,因此添加了EOF):

field1,en,field3
field1,de,field3

EOF

writerow should take a list of fields as argument: 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)               

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM