简体   繁体   中英

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.

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 .

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM