0

config.ini という構成ファイルで、jvm_args という特定のパラメーターを検索する必要があります。

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

ファイル内でこのパラメーターを見つけて、その値に何かを追加する方法を知る必要があります (つまり、文字列 some_value3 に文字列を追加します)。

4

4 に答える 4

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
于 2012-06-13T06:06:41.263 に答える
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も確認してください

于 2012-06-13T05:37:20.157 に答える
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
于 2012-06-13T06:09:59.030 に答える
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)
于 2012-06-13T06:22:22.517 に答える