1

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

Grace
  • 13
  • 1
  • 7
  • You (appreantly) already have code to convert the text file into dictionary `d`. You need to update that and then overwrite the whole file with the whole dictionary if you want to preserve existing contents. If you can figure that out, please [edit] your question and add the code that you currently have to convert the file into a dictionary (so it's a [mre]). – martineau Sep 01 '20 at 16:12
  • I've edited to include my code. Thank you. – Grace Sep 01 '20 at 16:16
  • try change the `open(file,'r+')` to `open(file,'a+')`. See [this SO question](https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function) to more details – Eduardo Coltri Sep 01 '20 at 16:18
  • I just tried and the result is the same – Grace Sep 01 '20 at 16:24

1 Answers1

0

Here's how to implement what I suggested in a comment. I also made a few other changes to improve the code and make if follow PEP 8 - Style Guide for Python Code guidelines:

import itertools

def read_data(file):
    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
    return d

def write_data(file, d):
    with open(file, 'w') as f:
        for key, values in d.items():
            f.write(key + '\n')
            for value in values:
                f.write(value + '\n')
            f.write('\n')

def add_info(file):
#    original_name = input("Please enter the name you would like to modify? ").upper()
#    additional_info = input("Enter information you would like to add? ")

    # hardcoded for testing
    original_name = "watermelon".upper()
    additional_info = "hard"

    d = read_data(file)
    d.setdefault(original_name, []).append(additional_info)
    write_data(file, d)


file = 'fruit_info.txt'  #file path
add_info(file)
martineau
  • 119,623
  • 25
  • 170
  • 301