mst*_*fan 8 python file-io configuration-files text-manipulation python-3.x
我需要通过python编辑配置文件,我尝试在stackoverflow和google上搜索,但它们不能覆盖我的情况,因为我需要替换文件中的行并在搜索中执行匹配.
另外,我发现的内容涵盖如何为一行做,我将在文件中执行至少8行替换,我想知道是否有更干净,更优雅的方式这样做比放10替换(foo) ,bar)线条.
我需要"匹配"像"ENABLEPRINTER","PRINTERLIST","PRNT1.PORT"这样的行.我想匹配这些文本并忽略后面的内容(例如:"= PRNT1,PRNT2").
所以我会做类似的事情
replace('ENABLEPRINTER', 'y')
replace('PRINTERLIST', 'PRNT3)
Run Code Online (Sandbox Code Playgroud)
该文件如下所示:
ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2
PRNT1.PORT=9600
PRNT1.BITS=8
Run Code Online (Sandbox Code Playgroud)
另请注意,这些文件大约有100行,我需要编辑大约10行.
非常感谢您的帮助.
更新:
使用@JF Sebastian发布的代码,我现在收到以下错误:
configobj.ParseError: Parse error in value at line 611.
Run Code Online (Sandbox Code Playgroud)
该文件的第611行是:
log4j.appender.dailyRollingFile.DatePattern='.'yyyy-MM-d
Run Code Online (Sandbox Code Playgroud)
所以问题在于'性格'.
如果我注释掉那一行,脚本就可以正常使用@JF Sebastian发布的代码了.
import re
pat = re.compile('ENABLEPRINTER|PRINTERLIST|PRNT1.PORT')
def jojo(mat,dic = {'ENABLEPRINTER':'y',
'PRINTERLIST':'PRNT3',
'PRNT1.PORT':'734'} ):
return dic[mat.group()]
with open('configfile','rb+') as f:
content = f.read()
f.seek(0,0)
f.write(pat.sub(jojo,content))
f.truncate()
Run Code Online (Sandbox Code Playgroud)
之前:
ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2
PRNT1.PORT=9600
PRNT1.BITS=8
Run Code Online (Sandbox Code Playgroud)
后:
y=n
PRNT3==PRNT1, PRNT2
734=9600
PRNT1.BITS=8
Run Code Online (Sandbox Code Playgroud)
太明确了.说出什么是错误或弱点.
正则表达式的优点是它们可以很容易地调整到特定情况.
.
编辑:
我刚刚看到:
"我想做的是为变量分配一个新值"
你可以提前通知!
请问您之前/之后是否可以提供文件示例.
.
编辑2
这是更改文件中某些变量值的代码:
import re
from os import fsync
def updating(filename,dico):
RE = '(('+'|'.join(dico.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)'
pat = re.compile(RE)
def jojo(mat,dic = dico ):
return dic[mat.group(2)].join(mat.group(1,3))
with open(filename,'rb') as f:
content = f.read()
with open(filename,'wb') as f:
f.write(pat.sub(jojo,content))
#-----------------------------------------------------------
vars = ['ENABLEPRINTER','PRINTERLIST','PRNT1.PORT']
new_values = ['y','PRNT3','8310']
what_to_change = dict(zip(vars,new_values))
updating('configfile_1.txt',what_to_change)
Run Code Online (Sandbox Code Playgroud)
之前:
ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2
PRNT1.PORT=9600
PRNT1.BITS=8
Run Code Online (Sandbox Code Playgroud)
后:
ENABLEPRINTER=y
PRINTERLIST=PRNT3
PRNT1.PORT=8310
PRNT1.BITS=8
Run Code Online (Sandbox Code Playgroud)
如果文件格式正确,java.util.Properties那么您可以使用pyjavaproperties:
from pyjavaproperties import Properties
p = Properties()
p.load(open('input.properties'))
for name, value in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
p[name] = value
p.store(open('output.properties', 'w'))
Run Code Online (Sandbox Code Playgroud)
它不是很强大,但对其进行的各种修复可能会让后续的人受益。
要在短字符串中替换多次:
for old, new in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
some_string = some_string.replace(old, new)
Run Code Online (Sandbox Code Playgroud)
替换配置文件中的变量名称(使用configobjmodule):
import configobj
conf = configobj.ConfigObj('test.conf')
for old, new in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
conf[new] = conf[old]
del conf[old]
conf.write()
Run Code Online (Sandbox Code Playgroud)
如果replace('ENABLEPRINTER', 'y')你的意思是分配y给ENABLEPRINTER变量那么:
import configobj
ENCODING='utf-8'
conf = configobj.ConfigObj('test.conf', raise_errors=True,
file_error=True, # don't create file if it doesn't exist
encoding=ENCODING, # used to read/write file
default_encoding=ENCODING) # str -> unicode internally (useful on Python2.x)
conf.update(dict(ENABLEPRINTER='y', PRINTERLIST='PRNT3'))
conf.write()
Run Code Online (Sandbox Code Playgroud)
似乎configobj不兼容:
name = '.'something
Run Code Online (Sandbox Code Playgroud)
你可以引用它:
name = "'.'something"
Run Code Online (Sandbox Code Playgroud)
或者:
name = '.something'
Run Code Online (Sandbox Code Playgroud)
或者
name = .something
Run Code Online (Sandbox Code Playgroud)
conf.update()做类似的事情:
for name, value in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
conf[name] = value
Run Code Online (Sandbox Code Playgroud)