0

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

cytings
  • 59
  • 9
  • Make sure you post the code actually used and the exact output it generates. Your code works as you want as typed. Also `file.close()` is unnecessary. The `with` will close the file. – Mark Tolonen Jun 28 '21 at 15:23

2 Answers2

2

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

birgador
  • 101
  • 4
1

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.

A.M. Ducu
  • 892
  • 7
  • 19
  • Overly complicated. @user2556520 answer is correct (no need for `for` and wrapping `[line]` as a list) and what the OP originally has in the question, so the question needs editing to show real code and real output. – Mark Tolonen Jun 28 '21 at 15:28