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
{'1': '1', '2': '2', '3': '3'}{'4': '4', '5': '5', '6': '6'}
Kyle Tennison :
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.\nYou can fix this by using a json format–like you imported:\nimport json\n\nmydic = {}\n\n# Read existing data\nwith open('cd.json', 'r') as jsonFile:\n mydic = json.load(jsonFile)\n\n# Get usernames and passwords\nfor i in range(3):\n uname = input("enter uname\\n")\n pwd = input("enter pwd\\n")\n\n mydic[uname] = pwd\n\nprint(mydic)\n\n\n# Write new values\nwith open('cd.json', 'w') as jsonFile: \n json.dump(mydic, jsonFile, indent=4, sort_keys=True)\n\n\nFirst 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.",
2022-07-09T06:49:41
azro :
You need to handle the content in the file as JSON, that's the easiest way to update the content, not handling as string version of dictionnary that you would append\nI used pathlib.Path to facilitate the file interactions\nimport json\nfrom pathlib import Path\n\nfile = Path("cd.json")\n\nif file.exists(): # load existing data\n mydic = json.loads(file.read_text())\nelse: # create new\n mydic = {}\n\n# add more data\nfor i in range(3):\n uname = input("enter uname\\n")\n pwd = input("enter pwd\\n")\n mydic[uname] = pwd\n\nprint(mydic)\n\n# save in file\nfile.write_text(json.dumps(mydic))\n\n# load back to verify\nmydic = json.loads(file.read_text())\nprint(mydic)\n",
2022-07-09T06:42:47