【问题标题】:Find a string in a file and replace the whole line [duplicate]在文件中查找字符串并替换整行[重复]
【发布时间】:2018-04-14 10:02:26
【问题描述】:

我最近对 ​​python 很陌生,正在尝试编写一个脚本。 在文件中搜索字符串并替换整行的最简单方法是什么。我发现 re.sub 可以做到这一点,但没有什么具体到我可以做到的。

例如:

    #configuration file
    Stuff that configures a file

    #configuration file
    Port 22

通过搜索配置

此命令是否还有不同的功能,例如搜索字符串 在一行的中间并替换它之后的所有内容。

【问题讨论】:

标签: python linux scripting


【解决方案1】:

您可以使用replace()替换端口号。

with open('resume.txt', 'r') as file:
    file_data = file.read()
    upd_port = file_data.replace('22', '4832')
with open('resume.txt', 'w') as file:
    file.write(upd_port)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多