Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write dictionary to a text file properly

I am trying to create a text file with dictionary storing some value so that I can retrieve it later but the write creates multiple dictionary how can I create only a single dictionary also the type of data is returned is as string how can I use it as dictionary, kindly pardon I am new to python,

I tried with json dump method but I was getting typeerror-object-of-type-method-is-not-json-serializable

import json

mydic = {}

for i in range(3):
    uname = input("enter uname\n")
    pwd = input("enter pwd\n")

    mydic[uname] = pwd

print(mydic)


with open("cd.txt","a+") as file:
    file.write(str(mydic))


with open("cd.txt","r") as file:
    data = file.read()
    print(data,type(data))

Data is getting saved as below 1-3 I gave input in first attempt 4 -6 for second attempt U can see 2 different dictionay got created

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'1': '1', '2': '2', '3': '3'}{'4': '4', '5': '5', '6': '6'}

>Solution :

You are adding the string conversion of your dictionary onto the file. Each time you run your program, the a+ flag tells it to append as a string.

You can fix this by using a json format–like you imported:

import json

mydic = {}

# Read existing data
with open('cd.json', 'r') as jsonFile:
    mydic = json.load(jsonFile)

# Get usernames and passwords
for i in range(3):
    uname = input("enter uname\n")
    pwd = input("enter pwd\n")

    mydic[uname] = pwd

print(mydic)


# Write new values
with open('cd.json', 'w') as jsonFile:   
    json.dump(mydic, jsonFile, indent=4, sort_keys=True)

First we read the existing values, then we run through the code you wrote to get usernames and passwords, and finally, we save all the data to a json file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading