Python: Write a dictionary to a text file (CSV

2019-09-09 22:13发布

问题:

I'm a novice Python programmer so the answer may be simple. However, I've spent several days researching this single question and I'm stumped. This is also my first Stack Overflow post, so please be kind if I'm breaking some rule here. :)

Using Python, I want to write two fields in multiple rows to a new text file, and on a later run read that text file into a new dictionary to reference the previous values.

I am testing code that I found here: Example code. The solution provided has 64 up-votes and is marked as the best answer by the asker. So it seems to be correct for most people.

My test code succeeds in creating an initial dictionary mydict and saving it to a text file. However, when I attempt to read the text file back into a new dictionary mydict2, I get...nothing...nothing at all, no error message or anything, no clue, just nothing.

What am I missing here?

Here is my test code:

import csv

mydict = {1:11,2:22,3:33}
print mydict
print mydict[1]

writer = csv.writer(open('dict.csv', 'wb'))
for key, value in mydict.items():
   writer.writerow([key, value])

reader = csv.reader(open('dict.csv', 'rb'))
mydict2 = dict(reader)

print mydict2

Here are the contents of the text file that it creates:

1,11
2,22
3,33

Here are the results displayed when I run the test code:

{1: 11, 2: 22, 3: 33}
11
{}

As you can see in the first two lines of results output, the initial output dictionary, mydict, is created correctly and displays a referenced value. However, the third line of output displays the contents of the new dictionary, mydict2, which should have read the data from the text file. However, the text file contents were somehow not read to the new dictionary, which is empty.

How can I fix this to load the text file contents into the dictionary?

回答1:

The problem is not closing your files. Your original file was not completely flushed to disk. The with statement will automatically close files when the with block exits.

import csv

mydict = {1:11,2:22,3:33}
print mydict
print mydict[1]

with open('dict.csv','wb') as f:
    writer = csv.writer(f)
    for key, value in mydict.items():
        writer.writerow([key, value])

with open('dict.csv','rb') as f:
    reader = csv.reader(f)
    mydict2 = dict(reader)

print mydict2

Output:

{1: 11, 2: 22, 3: 33}
11
{'1': '11', '3': '33', '2': '22'}


回答2:

I'm not sure the following is at all the most elegant answer, but apparently supplying an absolute path to the .csv file helped. The following should provide you with the desired dictionary object, read from the csv you've created:

import csv

mydict = {1:11,2:22,3:33}
print(mydict)
print(mydict[1])

with open('C:\\Python27\\dict.csv', 'wb') as writer:
   writer = csv.writer(writer)
   for item in mydict.items():
      writer.writerow(item)

with open('C:\\Python27\\dict.csv', 'rb') as reader:
   reader = csv.reader(reader)
   for line in reader:
       mydict2[int(line[0])] = int(line[1])
   #mydict2 = {line[0]:line[1] for line in reader} ...build mydict2 as a comprehension.

print(mydict2)

Best Luck!



回答3:

And then there's this. It will close the file, also. Thanks for the coaching guys!

import csv

mydict = {1:11,2:22,3:33}
print mydict
print mydict[1]

f = open('dict.csv', 'wb')
writer = csv.writer(f)
for key, value in mydict.items():
   writer.writerow([key, value])
f.close()

f = open('dict.csv', 'rb')
reader = csv.reader(f)
mydict2 = dict(reader)
f.close()

print mydict2