python - 如何:从字典中读取并附加到它
问题描述
我想要做的是,每次用户输入新条目时,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中使用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
推荐阅读
- hive - 在 hive 中的 collect_list() 中排序
- python-3.x - 如何在python中插入分数计数器
- php - Prestashop:如果产品有库存或缺货(允许订购),如何显示默认标签?
- java - 将文本字段数据从一个类移动到另一个/问题时将其加载到数据库中
- sql-server - SQL 按日/月运行总和
- machine-learning - GCE VM 无法连接到 TPU
- firebase - 持久性脱机时出现 Node.js Firestore SDK 错误
- vue.js - Vue v-用于条件样式
- javascript - 在进行下一步之前提交 Javascript
- arrays - 我的 for 循环不会显示我的对象,但不会出现错误