我有一个这样的文本文件:
line 1
line 2
line 3
CommandLine arguments "render -h 192.168.1.1 -u user -p pass"
line 5
我想替换 IP 地址并就地写入文件。棘手的部分是,行的顺序可能不同,并且命令行参数可能以不同的顺序编写。所以我需要找到以 CommandLine 开头的行,然后替换 -h 和下一个 - 之间的字符串。
到目前为止,我可以使用以下代码获取旧 IP 地址,但我不知道如何替换它并写入文件。我是 Python 初学者。
with open(the_file,'r') as f:
for line in f:
if(line.startswith('CommandLine')):
old_ip = line.split('-h ')[1].split(' -')[0]
print(old_ip)
最佳答案
尝试使用 fileinput
import fileinput, re
filename = 'test_ip.txt'
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(re.sub("-h \S+ -u", "-h YOUR_NEW_IP_HERE -u", line), end='')
关于python - 在文本文件中的两个单词之间查找/替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49624212/