Reputation: 1694
Hi I want to save a dictionary to csv, then input it. However on both output and input, I met some issues.
For output I tried: (D_FINAL is the dictionary)
f = open("D_FINAL.csv", "w")
writer = csv.writer(f)
for k, v in D_FINAL.items():
writer.writerow([k, v])
f.close
It works fine but when I want to open the csv, it says the file is locked from editting
For input I tried
import csv
dict = {}
r = open('D_FINAL3.csv', 'r')
for k, v in csv.reader(r):
dict[k] = v
r.close()
but I got error
ValueError Traceback (most recent call last)
<ipython-input-92-d3e2b3081317> in <module>()
3 dict = {}
4 r = open('D_FINAL2.csv', 'r')
----> 5 for k, v in csv.reader(r):
6 dict[k] = v
7
ValueError: not enough values to unpack
(expected 2, got 0)
What's the correct way to do these ?
Upvotes: 2
Views: 122
Reputation: 140168
on windows (python 3), if you don't use open("D_FINAL.csv", "w",newline="")
, the resulting csv file has extra blank lines (because of the extra carriage return char inserted making end of lines like \r\r\n
).
Unfortunately, those double carriage return chars are read back not the same way: it generates a blank row after each valid data row. So unpacking fails because there aren't any elements in the row.
More on this nasty side-effect: CSV file written with Python has blank lines between each row
So when reading, you get a blank line.
Just do (and upgrade your python skills a notch):
with open("D_FINAL.csv", "w", newline="") as f: # python 2: use: "wb"
writer = csv.writer(f)
writer.writerows(D_FINAL.items())
(write in one go with writerows
, use a with
block so you don't miss the call to close
and the file isn't locked anymore)
Note that json
module is best suited to read & write dictionaries (if your need is serialization)
Aside: it's better to read back using a better technique too (it seems that the newline
thingy isn't really necessary when reading):
with open("D_FINAL.csv", "r", newline="") as f: # python 2: use: "rb"
writer = csv.reader(f)
output = {k:v for k,v in writer} # unpack+dictionary comprehension
Upvotes: 2
Reputation: 1650
Looking at the code you have given, it seems like you are not actually closing the file by calling f.close()
. Changing f.close
to f.close()
should help you get over this issue.
But remember you can improve your code by implementing a with block. for example,
with open("D_FINAL.csv", "w",newline="") as f:
writer = csv.writer(f)
for k, v in D_FINAL.items():
writer.writerow([k, v])
Upvotes: 1
Reputation: 1260
May be you can use pandas
for this purpose
import pandas as pd
pd.DataFrame.from_dict(data=D_FINAL, orient='index').to_csv('D_FINAL.csv')
Hope this helps.
Upvotes: 0