Reputation: 29
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'}
Upvotes: 1
Views: 2119
Reputation: 1420
Try writing the dictionary as Pandas Dataframe in a csv file. It's much simpler to write and read from an csv file. And in future if you are having multiple dictionaries then you can just make a list of dicts and write to the csv file.
import pandas as pd
df=pd.DataFrame([your_dictionary])
df.to_csv(file_name)
#read csv
read_df = pd.read_csv(file_name)
dict_list=read_df.to_dict('records') #this will give you the list of dictionaries
Upvotes: 0
Reputation: 56
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.
Upvotes: 2
Reputation: 54168
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
I used pathlib.Path
to facilitate the file interactions
import json
from pathlib import Path
file = Path("cd.json")
if file.exists(): # load existing data
mydic = json.loads(file.read_text())
else: # create new
mydic = {}
# add more data
for i in range(3):
uname = input("enter uname\n")
pwd = input("enter pwd\n")
mydic[uname] = pwd
print(mydic)
# save in file
file.write_text(json.dumps(mydic))
# load back to verify
mydic = json.loads(file.read_text())
print(mydic)
Upvotes: 1