syntax
syntax

Reputation: 203

Replace Multiple Lines in a File using Python

I have a script that reads in values from one file and uses them to update fields in another file. It works great if I'm only doing one update, but if I add more (commented line) it breaks.

import re

def update_template():
    with open("dest.txt", "r") as template:
        lines = template.readlines()
    with open("dest.txt", "w") as template:
        for line in lines:
            template.write(re.sub(field_one, one, line))
            template.write(re.sub(field_two, two, line))  # <-- breaks here

with open('source.txt') as source:
    for line in source:
        one = "value1"
        two = "value2"
        field_one = "replace1"
        field_two = "replace2"
        update_template();

Calling the function for each update works, but I have a lot of data so I'd rather not do that. Any ideas?

Edit: If I have the following in dest.txt:

replace1
replace2

Post-run I end up with:

value1
value1
value1
replace1
replace2
value2
value2
value2

There should only be 'values' in there...

Upvotes: 1

Views: 1974

Answers (1)

Engineero
Engineero

Reputation: 12908

It looks like you are trying to write the same line to the file twice, which may be giving you a problem. Try doing all of your modifications to line first, and then writing to the file:

with open("dest.txt", "w") as template:
  for line in lines:
    line = re.sub(field_one, one, line)  # modify first
    line = re.sub(field_two, two, line)
    template.write(line)  # write once after modifying

It seems to work on my machine when tested.

Upvotes: 1

Related Questions