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?
And then there's this. It will close the file, also. Thanks for the coaching guys!
The problem is not closing your files. Your original file was not completely flushed to disk. The
with
statement will automatically close files when thewith
block exits.Output:
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:
Best Luck!