python搜索字符串并使用正则表达式将其追加

python搜索字符串并使用正则表达式将其追加,python,regex,Python,Regex,我需要在一个名为config.ini的配置文件中搜索一个名为jvm_args的特定参数 **contents of config.ini: first_paramter=some_value1 second_parameter=some_value2 jvm_args=some_value3** 我需要知道如何在我的文件中找到这个参数,并在它的值中添加一些内容(例如,在字符串some_value3中添加一个字符串) 您可以使用 同时选中您可以使用的 如果您“只是”想在ini文件中查找键和值,我

我需要在一个名为config.ini的配置文件中搜索一个名为jvm_args的特定参数

**contents of config.ini:
first_paramter=some_value1
second_parameter=some_value2
jvm_args=some_value3**
我需要知道如何在我的文件中找到这个参数,并在它的值中添加一些内容(例如,在字符串some_value3中添加一个字符串)

您可以使用

同时选中您可以使用的

如果您“只是”想在ini文件中查找键和值,我认为configparser模块比使用regexp更好。不过,configparser断言该文件具有“节”

下面是configparser的文档:-底部是有用的示例。configparser还可用于设置值和写出新的.ini文件

输入文件:

$ cat /tmp/foo.ini 
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3
代码:

输出文件:

$ cat /tmp/foo.ini
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3 some_value4
如果您“只是”想在ini文件中查找键和值,我认为configparser模块比使用regexp更好。不过,configparser断言该文件具有“节”

下面是configparser的文档:-底部是有用的示例。configparser还可用于设置值和写出新的.ini文件

输入文件:

$ cat /tmp/foo.ini 
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3
代码:

输出文件:

$ cat /tmp/foo.ini
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3 some_value4

正如avasal和tobixen所建议的,您可以使用python模块来实现这一点。例如,我使用了这个“config.ini”文件:

并运行了以下python脚本:

import ConfigParser

p = ConfigParser.ConfigParser()
p.read("config.ini")
p.set("section", "jvm_args", p.get("section", "jvm_args") + "stuff")
with open("config.ini", "w") as f:
    p.write(f)
运行脚本后,“config.ini”文件的内容为:

[section]
framter = some_value1
second_parameter = some_value2
jvm_args = some_value3**stuff

正如avasal和tobixen所建议的,您可以使用python模块来实现这一点。例如,我使用了这个“config.ini”文件:

并运行了以下python脚本:

import ConfigParser

p = ConfigParser.ConfigParser()
p.read("config.ini")
p.set("section", "jvm_args", p.get("section", "jvm_args") + "stuff")
with open("config.ini", "w") as f:
    p.write(f)
运行脚本后,“config.ini”文件的内容为:

[section]
framter = some_value1
second_parameter = some_value2
jvm_args = some_value3**stuff

没有
regex
您可以尝试:

with open('data1.txt','r') as f:
    x,replace=f.read(),'new_entry'
    ind=x.index('jvm_args=')+len('jvm_args=')
    end=x.find('\n',ind) if x.find('\n',ind)!=-1 else x.rfind('',ind)
    x=x.replace(x[ind:end],replace)

with open('data1.txt','w') as f:
    f.write(x)

没有
regex
您可以尝试:

with open('data1.txt','r') as f:
    x,replace=f.read(),'new_entry'
    ind=x.index('jvm_args=')+len('jvm_args=')
    end=x.find('\n',ind) if x.find('\n',ind)!=-1 else x.rfind('',ind)
    x=x.replace(x[ind:end],replace)

with open('data1.txt','w') as f:
    f.write(x)
检查此项:检查此项: