Home > Back-end >  overwrite a line of text inside a text file that begins with a string in python
overwrite a line of text inside a text file that begins with a string in python

Time:11-16

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:

def func(my_dict):
   # Read in the file
   with open('myfile.txt', 'r') as file :
       filedata = file.read()

       # Replace the target string
       filedata = filedata.replace('colors', my_dict)

   # Write the file out again
   with open('myfile.txt', 'w') as file:
       file.write(filedata)           

The problem is that I get an output like:

myfile.txt
green, black = red, purple, orange, blue

CodePudding user response:

New version preserving text that doesn't have an equals sign

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

def func(my_dict):
    # 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 a new list
    new_lines = []
    # Process each line of the file's contents
    for line in lines:
        # If it doesn't have an '=', just add it and continue iteration
        if "=" not in line: 
            new_lines.append(line)
            continue

        key, value = line.split("=")

        # if the key is in replacement dictionary, append a line with the new value
        if key.strip() in my_dict.keys():
            new_lines.append(f'{key.strip()} = {my_dict[key.strip()]}')
        # else just add the old line
        else:
            new_lines.append(line)

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

func(my_dict)

Old version

# 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))

CodePudding user response:

You have given a function that takes as my_dict but you used as a string in replace method. You should have given how you called function. However, this is the solution. Comments explains what happenings. Instead of reading from file, I just created a string same as your file content. You can just change that related part. We used split method to have as key and value pairs.

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


def func(my_dict):
    filedata = """colors = red, purple, orange, blue\nfood = burgers, pizza, hotdogs \nanimals = birds, dogs, cats"""
    #get lines of line
    lines = filedata.split("\n")
    #this will store our final text
    fileDict = {}
    for line in lines:
        #get key from file/source
        key = line.split(" = ")[0]
        if(key in my_dict.keys()):
            #if key exist in your dict, change it with your my_dict value
            newValues = my_dict[key]
            fileDict[key] = newValues
        else:
            #if key not exist in your my_dict, use file/source values
            fileDict[key] = line.split(" =")[1]

    #stringify dictionary
    text = ""
    for key,value in fileDict.items():
        text  = f"{key} = {value}\n" 

    #write to file
    with open('myfile.txt', 'w') as file:
       file.write(filedata)  

func(my_dict)

CodePudding user response:

You need to split the sentence (line) on the equal sign and replace the second part of the equal sign. This can expand to your other data as well

with open("myfile.txt") as file:
    for line in file.readlines():
        if "colors" in line:
            filedata = line.replace(line.split(" = ")[1], my_dict["colors"])

When you write, the syntax should be the same.

  • Related