modify a text file with values from a dictionary

Question:

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..

Asked By: magicsword

||

Answers:

There’s no need to create a dictionary from the file. Just replace the lines that match what’s in your new dictionary.

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

with open('myfile.txt', 'r') as file:
    filedata = file.read()

# Now split the rows on newline
lines = filedata.split('n')

# Process each line of the file's contents
for i, line in enumerate(lines):
    # If it doesn't have an '=', skip the line
    if "=" not in line: continue

    key, value = line.split("=")
    key = key.strip()
    if key in my_dict:
        lines[i] = f'{key} = {my_dict[key]}'

with open('myfile.txt', 'w') as file:
    # join the new lines for the file with a newline character
    file.write('n'.join(lines)) 
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.