【问题标题】:python search for a string and append to it using regular expressionpython搜索字符串并使用正则表达式附加到它
【发布时间】:2012-06-13 05:26:36
【问题描述】:

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

**contents of config.ini:
first_paramter=some_value1
second_parameter=some_value2
jvm_args=some_value3**

我需要知道如何在我的文件中找到这个参数并将一些内容附加到它的值(即附加一个字符串到字符串 some_value3)。

【问题讨论】:

标签: python regex


【解决方案1】:

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

configparser 的文档在这里:http://docs.python.org/library/configparser.html - 底部有用的示例。 configparser 还可用于设置值和写出新的 .ini 文件。

输入文件:

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

代码:

#!/usr/bin/python3

import configparser

config = configparser.ConfigParser()
config.read("/tmp/foo.ini")
jvm_args = config.get('some_section', 'jvm_args')
print("jvm_args was: %s" % jvm_args)

config.set('some_section', 'jvm_args', jvm_args + ' some_value4')
with open("/tmp/foo.ini", "w") as fp:
    config.write(fp)

输出文件:

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

【讨论】:

    【解决方案2】:

    您可以使用re.sub

    import re
    import os
    
    file = open('config.ini')
    new_file = open('new_config.ini', 'w')
    for line in file:
        new_file.write(re.sub(r'(jvm_args)\s*=\s*(\w+)', r'\1=\2hello', line))
    file.close()
    new_file.close()
    
    os.remove('config.ini')
    os.rename('new_config.ini', 'config.ini')
    

    还要检查ConfigParser

    【讨论】:

      【解决方案3】:

      正如 avasal 和 tobixen 所建议的,您可以使用 python ConfigParser 模块来执行此操作。比如我拿了这个“config.ini”文件:

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

      并运行这个 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
      

      【讨论】:

        【解决方案4】:

        没有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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-26
          • 1970-01-01
          • 2012-05-28
          • 1970-01-01
          • 1970-01-01
          • 2019-10-17
          • 1970-01-01
          相关资源
          最近更新 更多