Home:ALL Converter>modify a text file with values from a dictionary

modify a text file with values from a dictionary

Ask Time:2022-11-16T03:49:31         Author:magicsword

Json Formatter

I have a text file as follows:

myfile.txt

[items]
colors = red, purple, orange, blue
[eat]
food = burgers, pizza, hotdogs 
[furry]
animals = birds, dogs, cats

I have a dictionary:

my_dict = {'colors':'green, black','animals':'donkey, tigers'}

I want to open the file myfile.txt and search for the keys inside the file and replace the lines with the values of my_dict so that myfile.txt should look like:

myfile.txt

[items]
colors = green, black
[eat]
food = burgers, pizza, hotdogs 
[furry]
animals = donkey, tigers

I've tried doing something like:

    # Get the file contents like you were already doing
with open('myfile.txt', 'r') as file:
    filedata = file.read()

# Now split the rows on newline
lines = filedata.split('\n')
# Create an empty dictionary
pairs = {}
# Process each line of the file's contents
for line in lines:
    # If it doesn't have an '=', skip the line
    if "=" not in line: continue
    key, value = line.split("=")
    # fill the dictionary with the keys and values in the file
    pairs[key.strip()] = value.strip()

my_dict = {'colors': 'green, black', 'animals': 'donkey, tigers'}

# replace the previous files values with any new values from the new dictionary
for k, v in my_dict.items():
    pairs[k] = v

# format the dictionary back into a line of text "colors = blue, black, etc."
new_lines = [f'{k} = {v}' for k, v in pairs.items()]

with open('myfile.txt', 'w') as file:
    # join the new lines for the file with a newline character
    file.write('\n'.join(new_lines))  

     

The problem is that I get an output like:

myfile.txt
colors = red, purple, orange, blue
food = burgers, pizza, hotdogs 
animals = birds, dogs, cats

Where all the text in the brackets has been discarded. I need to keep the headings too [items], [eat], etc..

Author:magicsword,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74451368/modify-a-text-file-with-values-from-a-dictionary
yy