首页 > 解决方案 > 如何:从字典中读取并附加到它

问题描述

我想要做的是,每次用户输入新条目时,dictionary都应该在 my 中输入一个新条目list_1.txt,然后从中读取。
我得到了这个"adding content to list_1.txt"部分,但我不知道我怎么可能从中dictonary读回。

def dictionary():
    dict1 = {"name": "xyz",
             "age": 25,
             "hobby": "Dancing"}

if input("Do you want to update the values?[y/n]: ") == "y":
    dict1["name"] = str(input("Change the name to: "))
    print(dict1["name"])
    dict1["age"] = int(input("Change the age to: "))
    print(dict1["age"])
    dict1["hobby"] = str(input("Change the hobby to: "))
    print(dict1["hobby"])
elif input() != "y":
    print("No valid input");
elif input() == "n":
    print("Here is the current Data: " + str(dict1))
    sys.exit()
print(dict1)

appendFile = open('list_1.txt','a')
appendFile.write("\n" + str(dict1))
appendFile.close()

这是代码的当前状态。我已经尝试"readMe = open("list_1.txt","r").read()"在内部创建和调用它,"dict1"但你可以想象它出了严重的错误。如果您能提供任何帮助和建议,我将不胜感激。
PS:我知道我的菜单有问题,但我还没有花时间。这只是一个学习python的小项目。

标签: python

解决方案


在python中使用json模块

import json

#assming folling is content of your text file
# {
#     "name": "xyz",
#     "age": 25,
#     "hobby": "Dancing"
# }


#context manager // auto close file outside "with" clause
with open("list_1.txt",'r') as file:

    #convert  string '{"name": "xyz","age": 25, "hobby": "Dancing" }' into
    #dictionary dict1
    dict1=json.loads( file.read()  )  


if input("Do you want to update the values?[y/n]: ") == "y":
    dict1["name"] = str(input("Change the name to: "))
    print(dict1["name"])
    dict1["age"] = int(input("Change the age to: "))
    print(dict1["age"])
    dict1["hobby"] = str(input("Change the hobby to: "))
    print(dict1["hobby"])
elif input() != "y":
    print("No valid input");
elif input() == "n":
    print("Here is the current Data: " + str(dict1))
    sys.exit()
print(dict1)

# appendFile = open('list_1.txt','a')
# appendFile.write("\n" + str(dict1))
# appendFile.close()

#use this instead
with  open('list_1.txt','w') as file:
    #convert dict to string
    content = json.dumps(dict1)
    file.write(content)


你也可以使用 numpy

np.save('list_1.npy', dictionary)
#file extension must me .npy

推荐阅读