1

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

1
  • 2
    Surely you're not opening the same file twice? You said you were updating fields in another file, right? Commented Jul 24, 2015 at 21:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.