简体   繁体   中英

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. 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

thanks so much for the support.

Here an answer using DictWriter instead, but an amount of guesswork based on the structure of data. 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):

field1,en,field3
field1,de,field3

EOF

writerow should take a list of fields as argument:

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)               

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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