【发布时间】:2020-09-01 15:25:27
【问题描述】:
我有一个文本文件转字典
文本文件:
banana
delicious
yellow
watermelon
big
red
orange
juicy
vitamin c
我要转换的代码是:
file = "C:\\Users\\user\\Downloads\\file.txt" #file path
d= {}
with open(file, 'r') as f:
for empty_line, group in itertools.groupby(f, lambda x: x == '\n'):
if empty_line:
continue
fruit, *desc = map(str.strip, group)
d[fruit] = desc
d= {k.upper():v for k,v in d.items()} #capitalise the names
转换成字典d后:
{'BANANA' : ['delicious', 'yellow'],
'WATERMELON' : ['big', 'red'],
'ORANGE' : ['juicy', 'vitamin c']}
我正在努力将附加值添加到键中,不仅是字典本身,还有原始文件。但是我当前的代码删除了所有键和值,除了我正在添加信息的那个。而且也不把钥匙还给我。
def Add_Info():
original_name = input("Please enter the name you would like to modify? ").upper()
additionalinfo = input("Enter information you would like to add? ")
with open(file,'r+') as f:
data = f.read()
data = d[original_name].append(additionalinfo)
f.truncate(0)
f.seek(0)
f.write("\n".join(d[original_name]))
f.close()
for eg, if
original_name = watermelon
additionalinfo = hard,
in the file, it only returns me
big
red
hard
相反,我希望剩余的水果、香蕉和橙子保持不变,只需将值 hard 添加到 watermelon
下的文件中【问题讨论】:
-
您(显然)已经拥有将文本文件转换为字典
d的代码。如果要保留现有内容,您需要更新它,然后用整个字典覆盖整个文件。如果你能弄清楚,请edit你的问题并添加你当前必须将文件转换为字典的代码(所以它是minimal reproducible example)。 -
我已编辑以包含我的代码。谢谢。
-
尝试将
open(file,'r+')更改为open(file,'a+')。更多详情请见this SO question -
我刚试了,结果还是一样
标签: python python-3.x dictionary key key-value