Python 将字典读取到文件只会覆盖新信息
我已将文本文件读入词典,使用函数在词典中添加/删除记录,然后将其写回文本文件。文本文件的格式如下:Python 将字典读取到文件只会覆盖新信息,python,Python,我已将文本文件读入词典,使用函数在词典中添加/删除记录,然后将其写回文本文件。文本文件的格式如下: First Name 2018-11-05 10:12:15 First string Second string Third string Second Name 2014-01-02 14:21:11 First string Second string Third string 这是我代码的一部分:
First Name
2018-11-05 10:12:15
First string
Second string
Third string
Second Name
2014-01-02 14:21:11
First string
Second string
Third string
这是我代码的一部分:
name = {'First Name':['2018-11-05 10:12:15','First string', 'Second String',
'Third String']} and so on
def addName(names):
print("Adding to name list")
while True:
answer = input("Enter name to add or <ENTER> to exit: ")
if answer == "":
print("Exiting Add Names")
break
elif answer in name:
print("Name already exist")
elif answer not in [name]:
new_name_info = str(input("Enter name info: "))
new_name_dict = {answer: [datetime.now().strftime("%Y-%m-%d %H:%M:%S"), new_plant_info]}
name.update(new_names_dict)
print("Add new name info successful.")
break
def Write_back_into_file(diction):
print("Writing it back and exiting")
with open("filename", "w") as file:
for key in diction.keys():
namess = list(name[key])
file.write(key + "\n" + "".join(namess) + "\n")
name={'First name':['2018-11-05 10:12:15','First string','Second string',',
'第三个字符串']}等等
def addName(名称):
打印(“添加到姓名列表”)
尽管如此:
回答=输入(“输入要添加或退出的名称:”)
如果答案==“”:
打印(“正在退出添加名称”)
打破
以姓名回答:
打印(“名称已存在”)
如果答案不在[名称]中:
新建名称信息=str(输入(“输入名称信息”))
new_name_dict={回答:[datetime.now().strftime(“%Y-%m-%d%H:%m:%S”),new_plant_info]}
名称。更新(新名称)
打印(“添加新名称信息成功”)
打破
def写回文件(措辞):
打印(“写回并退出”)
打开(“文件名”、“w”)作为文件:
对于输入法。键():
名称=列表(名称[键])
file.write(键+“\n”+”.join(名称)+“\n”)
但是,不是将更新后的字典写回文件,而是仅使用添加到字典中的新键覆盖整个文件
我理解“w”模式的工作原理,但我希望在添加和删除记录后,更新的字典将写入文件
因此,我不确定如何将更新后的词典以原始格式写回文本文件。在输入错误旁边,类似的操作应该可以:
def Write_back_into_file(diction):
print("Writing it back and exiting")
with open("filename", "w") as file:
for key in diction.keys():
file.write(key + "\n" + "\n".join(diction[key]) + "\n\n")
当然,您必须将字典“name”传递给函数:
Write_back_into_file(name)
在这种情况下,追加将向我的文件中添加重复的条目。您提供的代码中有太多错误,无法确定它的作用。函数
addName()
接受names
作为参数,但函数中的代码从不引用它,而是在第8行测试answer in name
,而answer not in[name]
第10行。而name
本身的定义不在您提供的代码中。它似乎是一个dict
,因为您调用name.update()
,但如果是这样,则不在[name]中的测试答案将始终是False
,因为只有answer
是dict
,它才是True
,但它是input()
返回的字符串
值,所以更新呼叫不会发生。