简体   繁体   中英

Add new entry to existing csv with csv writer

Got a really simple problem. But can't figure out my mistake. I'm want to save a list csv_line = ["name 1", "value 1", "name 2", "value 2",...] of values which get updated in a specific time interval as a csv file. My current approchach (inspired by this post ) looks like:

with open("live_data.csv", "a", newline="") as file:

    writer = csv.writer(file)
    writer.writerow(csv_line)
    file.close()

which results in an output like:

n
a
m
e

1

v
a
...

when i clearly want my csv to look like:

entry1
entry2
...

Guess I'm missing something really obvious here...

Running

import csv

csv_line = ["name 1", "value 1", "name 2", "value 2"]
with open("live_data.csv", "a", newline="") as file:

    writer = csv.writer(file)
    writer.writerow(csv_line)

saves in live_data.csv name 1,value 1,name 2,value 2 Which I understand is what you intend to accomplish.

EDIT: I forgot to mention that with the with statement you don't need to close the file [1]


[1] https://docs.python.org/3/reference/compound_stmts.html#the-with-statement

This should work as intended:

import csv

csv_line = ["name 1", "value 1", "name 2", "value 2"]

with open("live_data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    for line in csv_line:
        writer.writerow([line])

When using with open syntax you no longer need to close the file. Also, when using writerow, the function expects a list input, so using a string as input will first transform it to list and then write it, therefore obtaining each letter in a different column.

Also, depending on your use case, you can use 'w' as option in open() if you only write it once. Otherwise, keeping 'a' will keep adding to that file.

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