简体   繁体   中英

How can I write each row to a csv file?

I currently have code that is writing to a csv file, however, it keesp replacing the first row of the file and overwriting it instead of writing of it.

NOTE: I have this function inside a for loop inside main().

def write_csv_report(filename, region, data, current, server1, server2=False):
    if not os.path.exists(os.path.dirname(filename)):
        try:
            dir = os.makedirs(os.path.dirname(filename))
            
            header = ['region','old_dns_server', 'proposed_dns_server1', 'proposed_dns_server2']
            data = [region, current, server1, server2]

            with open(filename, 'a') as file:
                writer = csv.writer(file)
                writer.writerow(header)
                writer.writerow(data)

        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise

When I run this function in my script, it writes to the file but only one entry is added.

Is there any suggestions or solution where I can add multiple entries? I have looked at other sage questions and googled but it looks like I already have the necessary changes needed to achieve this outcome, not sure what I'm missing.

For csv.writer (and csv.reader ), you need to open the file with newline='' .

You also write the header every time, which is a bit odd.

Here's a minimal example that does more-or-less what you want:

import csv

header = ['region','old_dns_server', 'proposed_dns_server1', 'proposed_dns_server2']

data1 = ['foo', 'bar', 'bar', 'quux']
data2 = ['foo1', 'bar1', 'bar1', 'quux2']

filename = 'test.csv'

with open(filename, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(header)
    writer.writerow(data1)

with open(filename, 'a', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(data2)

giving:

region,old_dns_server,proposed_dns_server1,proposed_dns_server2
foo,bar,bar,quux
foo1,bar1,bar1,quux2

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