I have a text file-turned-dictionary
text file:
banana
delicious
yellow
watermelon
big
red
orange
juicy
vitamin c
My code to convert is:
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
After converting into dictionary named d:
{'BANANA' : ['delicious', 'yellow'],
'WATERMELON' : ['big', 'red'],
'ORANGE' : ['juicy', 'vitamin c']}
I'm working on adding the additional values to the key not only to the dictionary itself but also to the original file. But my current code deletes all the key and values except the one I'm adding information. And also does not return me the key.
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
Instead, I would like the remaining fruits, banana and orange to remain untouched and just add the value hard into the file under watermelon