Reading/writing a dictionary to file problem :(

Joined
Mar 31, 2020
Messages
1
Reaction score
0
# python3.7.2

#so i wrote the contents of frequent dictionary to the file common_f



frequent ={'1':'11111','2':'222222','3':'33333','4':'44444'}



file = open('F:\\common_f','w')

file.write((frequent))

print((frequent))

file.close()

print('exit to system')

exit()





#then when i retrieve, i get a single line as follows

#{'1':'11111','2':'222222','3':'33333','4':'44444'},

# not 4 dictionary entries :



frequent={}



file = open('F:\\common_f','r')

frequent=file.read()

print(frequent)

file.close()









what am i doing wrong?
 
Joined
Mar 31, 2020
Messages
2
Reaction score
1
Hi!

First a thing to make it easier for us to view your code: use the insert > code option in the editor to make it more clear what is code and what is text of the post. For this small post it does not matter that much, but just something for in the future!

Second, I have worked your code into this working example:

Python:
import json

# Writing
frequent ={'1':'11111','2':'222222','3':'33333','4':'44444'}

f_json = json.dumps(frequent)

fd = open('common_f','w')

fd.write(f_json)

fd.close()

print('exit to system')

# Reading
fd = open('common_f','r')
f_json = json.load(fd)

print(f_json)

fd.close()
exit()

A couple of remarks:
  • Try not to use any technical names / full-on English names like 'file' or 'integer' or 'string' as any variable name. This not only causes confusion for many, but also might cause runtime or compile-time errors. Depending on the language of course.
    • For example, in the solution I changed the 'file' variable to fd meaning: File Descriptor. A standard used since the days of C ;).
  • The example uses the JSON standard, try to use it as well. It is a well established standard that helps a ton with these kind of examples. The standard Python library json will offer all the functionality you need, maybe nice for you to read into!
  • It might be since I am using Python 3.8. But for me fd.write(frequent) would not even work considering it is not a string but a dictionary object. Your Python version might have tried to make sense of it anyways and automatically casted the Dictrionary object to a String. Causing the single string result on the receiving end. Therefore it is advised to use the JSON library as shown in my code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top