2012-06-13 45 views
0

我需要尋找被稱爲稱爲config.ini文件蟒蛇搜索字符串和追加到它使用正則表達式

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

我需要知道如何找到這個配置文件jvm_args一定的參數參數在我的文件並附加一些東西到它的值,(即追加一個字符串字符串some_value3)。

+2

檢查此:http://stackoverflow.com/questions/7645252/python-configparser-wrapper/7648154#7648154 – avasal

回答

1

您可以使用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

2

如果你「只是」想找到鍵和值在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 
0

由於兩個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 
0

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