python - 在文本文件中的两个单词之间查找/替换字符串

标签 python string

我有一个这样的文本文件:

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/

相关文章:

python - PyMC3 高斯混合模型

python - 如何使用pip更新私有(private)包?

python - 在 postgres 中使用 sqlalchemy 访问复合数据类型

python - 删除 Python 中变量和字符串之间的空格

regex - 在 RegEx 中将空格转换为制表符

c# - 如何替换包含格式信息的字符串

python - 更改 tkinter 菜单的字体

python - 我已经使用 ubuntu 14.04 为 python PyQt4 应用程序创建了一个 docker 镜像,现在当我运行容器时,我想要访问 docker 主机 IP 和接口(interface)

c - 将数组中的随机字符串提取到 C 中的 printf 中

Swift - 特殊字符的编码和解码字符串