Saving a zip list in csv in Python

How can I write below a zip list to a csv file in python?

[{'date': '2015/01/01 00:00', 'v': 96.5},
 {'date': '2015/01/01 00:01', 'v': 97.0},
 {'date': '2015/01/01 00:02', 'v': 93.75},
 {'date': '2015/01/01 00:03', 'v': 96.0},
 {'date': '2015/01/01 00:04', 'v': 94.5}

I have this error:

_csv.Error: sequence expected

My code is here:

import csv
res = zip_list
csvfile = "/home/stm/PycharmProjects/isbak_trafik/example.csv"

with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(res)
+4
source share
3 answers

writer.writerows expects a sequence of values ​​to write a single line to a CSV file.

Using source code:

import csv
res =[{'date': '2015/01/01 00:00', 'v': 96.5}, {'date': '2015/01/01 00:01', 'v': 97.0}, {'date': '2015/01/01 00:02', 'v': 93.75}, {'date': '2015/01/01 00:03', 'v': 96.0}, {'date': '2015/01/01 00:04', 'v': 94.5}]
csvfile = "example.csv"
with open(csvfile, "w") as output:
  writer = csv.writer(output, lineterminator='\n')
  for line in res:
    date = line['date']
    value = line['v']
    writer.writerow([date, value])
+1
source

Since I found that csv.DictWriter is not transparent in its actions, I would recommend doing the following:

with open(csvfile, "w") as output:
    output.write(';'.join(list(res[0].keys()))+"\n")
    [output.write(';'.join(list(map(str, r.values())))+"\n") for r in res]
+2
source

Python DictWriter . , , . :

import csv

zip_list = [
    {'date': '2015/01/01 00:00', 'v': 96.5},
    {'date': '2015/01/01 00:01', 'v': 97.0},
    {'date': '2015/01/01 00:02', 'v': 93.75},
    {'date': '2015/01/01 00:03', 'v': 96.0},
    {'date': '2015/01/01 00:04', 'v': 94.5}]

csvfile = "/home/stm/PycharmProjects/isbak_trafik/example.csv"

with open(csvfile, "wb") as output:
    writer = csv.DictWriter(output, fieldnames=['date', 'v'])
    writer.writeheader()
    writer.writerows(zip_list)

:

date,v
2015/01/01 00:00,96.5
2015/01/01 00:01,97.0
2015/01/01 00:02,93.75
2015/01/01 00:03,96.0
2015/01/01 00:04,94.5
+1

Source: https://habr.com/ru/post/1627748/


All Articles