通过Python编辑配置文件

2024-05-20 01:07:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过python编辑一个配置文件,我尝试在stackoverflow和google上搜索,但它们并没有覆盖我的情况,因为我需要替换文件中的行并在搜索中执行匹配。

另外,我发现的内容涵盖了如何对一行进行替换,我将在文件中执行至少8行替换,我想知道是否有一种更干净、更优雅的方法来执行此操作,而不是总共放置10行替换(foo,bar)。

我需要“匹配”像“ENABLEPRINTER”、“PRINTERLIST”、“PRNT1.PORT”这样的行。 我想匹配这些文本并忽略以下内容(例如:“=PRNT1,PRNT2”)。

所以我会做些

replace('ENABLEPRINTER', 'y')
replace('PRINTERLIST', 'PRNT3) 

文件如下所示:

ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2

PRNT1.PORT=9600
PRNT1.BITS=8

另外请注意,这些文件大约有100行,我需要编辑其中的10行。

非常感谢你的帮助。

更新

使用@J.F.Sebastian发布的代码,我现在得到以下错误:

configobj.ParseError: Parse error in value at line 611.

文件的第611行是:

log4j.appender.dailyRollingFile.DatePattern='.'yyyy-MM-d

所以问题出在“性格”上。

如果我注释掉这一行,脚本就可以处理@J.F.Sebastian发布的代码了。


Tags: 文件代码编辑内容port配置文件google情况
2条回答

如果文件是^{}格式,则可以使用^{}

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'))

它不是很健壮,但是各种各样的修复方法可以使下一个来的人受益。


要在短字符串中多次替换:

for old, new in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
    some_string = some_string.replace(old, new)

要替换配置文件中的变量名(使用^{} module):

import configobj

conf = configobj.ConfigObj('test.conf')

for old, new in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
    conf[new] = conf[old]
    del conf[old]
conf.write()

如果您所说的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()

似乎configobj不兼容:

name = '.'something

你可以引用它:

name = "'.'something"

或:

name = '.something'

或者

name = .something

conf.update()执行类似的操作:

for name, value in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
    conf[name] = value
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()

之前:

ENABLEPRINTER=n 
PRINTERLIST=PRNT1, PRNT2  

PRNT1.PORT=9600 
PRNT1.BITS=8

之后:

y=n 
PRNT3==PRNT1, PRNT2  

734=9600
PRNT1.BITS=8

太简单了,无法确定。说出错误或弱点是什么。

正则表达式的优点是它们可以很容易地调整到特定的情况。

是的。

编辑:

我刚刚看到:

“我想做的是给变量赋一个新值”

你可以早点告诉我!

请给我一个前后文件的例子。

是的。

编辑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)

之前:

ENABLEPRINTER=n 
PRINTERLIST=PRNT1, PRNT2  

PRNT1.PORT=9600 
PRNT1.BITS=8

之后:

ENABLEPRINTER=y 
PRINTERLIST=PRNT3

PRNT1.PORT=8310 
PRNT1.BITS=8

相关问题 更多 >