Danny
Danny

Reputation: 5400

Search for a line that contains some text, replace complete line python

So I am trying to search for a certain string which for example could be: process.control.timeout=30, but the 30 could be anything. I tried this:

for line in process:
    line = line.replace("process.control.timeout", "process.control.timeout=900")
    outFile.write(line)

But this will bring me back process.control.timeout=900=30. I have a feeling I will need to use regex with a wildcard? But I'm pretty new to python.

Upvotes: 2

Views: 3138

Answers (3)

agf
agf

Reputation: 176780

Without regex:

for line in process:
    if "process.control.timeout" in line:
        # You need to include a newline if you're replacing the whole line
        line = "process.control.timeout=900\n" 
    outFile.write(line)

or

outFile.writelines("process.control.timeout=900\n" 
                      if "process.control.timeout" in line else line 
                         for line in process)

If the text you're matching is at the beginning of the line, use line.startswith("process.control.timeout") instead of "process.control.timeout" in line.

Upvotes: 4

Imran
Imran

Reputation: 90999

This is probably what you want (matching = and digits after = is optional). As you are searching and replacing in a loop, compiling the regex separately will be more efficient than using re.sub directly.

import re

pattern = re.compile(r'process\.control\.timeout(=\d+)?')

for line in process:
    pattern.sub('process.control.timeout=900', line)

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208465

You are correct, regex is the way to go.

import re
pattern = re.compile(r"process\.control\.timeout=\d+")
for line in process:
    line = pattern.sub("process.control.timeout=900", line)
    outFile.write(line)

Upvotes: 1

Related Questions