-2

I would like to loop on every lines from a .txt file and then use re.sub method from Python in order to change some contents if there is a specific pattern matcing in this line.

But how can I do that for two different pattern in the same file ?

For example, here's my code :

file = open(path, 'r')
output = open(temporary_path, 'w')

for line in file:
    out = re.sub("patternToChange", "patternToWrite", line) #Here I would like to also do the same trick with "patternToChange2 and patternToWrite2 also in the same file
    output .write(out)

Do you have any ideas ?

5
  • Could you please provide a very basic example of input and expected output? I couldn't quite catch the idea. Commented Aug 30, 2019 at 15:50
  • Can you provide a few sample lines from the file and also describe what you wish to find and what you wish to replace? From a pure stance, you're current code will literally find patternToChange and replace it with patternToWrite. Commented Aug 30, 2019 at 15:51
  • Can't you just run re.sub again, but taking out as its input, and using your new patterns? If you saved the result back to out, you wouldn't need to make any other changes. Commented Aug 30, 2019 at 15:54
  • Does the python syntax allow for re.sub(...).sub(...) in one line? If not, Scott's idea is correct where you would do out = re.sub(pattern1, write1, line) then out = re.sub(pattern2, write2, out) Commented Aug 30, 2019 at 16:00
  • Why don't you read the whole file into a string, do the 2 sub's on it, then write it back. It's the cleanest way. It's very rare a regex doesn't apply to spanned lines... Commented Aug 30, 2019 at 16:41

1 Answer 1

0

I think it'd be best to apply all of your regex(es) to the string, one at a time, before you write it to the file. Maybe something like this?

for line in file:
    out = re.sub('patternToChange', 'patternToWrite', line)
    out2 = re.sub('patternToChange2', 'patternToWrite2', out)
    output.write(out2)

The above code worked fine for me - try it here if you'd like. Also, be sure to .close() your files when you're done, or the output might not show up in them.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.