通过python编辑配置文件

发布于 2024-10-21 20:39:01 字数 886 浏览 4 评论 0原文

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

另外,我发现的内容涵盖了如何执行一行操作,我将在文件中执行至少 8 行替换,我想知道是否有比放置 10 次替换(foo ,栏)总共行。

我需要“匹配”诸如“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 行。

非常感谢您的帮助。

更新

使用@JF Sebastian 发布的代码,我现在收到以下错误:

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

文件的第 611 行是:

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

所以问题出在 ' 字符上。

如果我注释掉该行,则该脚本可以与@JF Sebastian 发布的代码一起正常运行。

I need to edit a configuration file through python and i tried searching on stackoverflow and google and they don't cover my situation, since i need to replace lines in the file and perform matches in my search.

Also, what i found covers how to do it for one line, i will be performing at least 8 line replacements in the file and I would like to know if there is a cleaner and more elegant way of doing this than putting 10 replace(foo, bar) lines altogether.

I need to "match" lines like "ENABLEPRINTER", "PRINTERLIST", "PRNT1.PORT".
I want to match thesse text and ignore whatever follows (ex: "=PRNT1, PRNT2").

So i would do something like

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

The file looks like this:

ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2

PRNT1.PORT=9600
PRNT1.BITS=8

Also note these files are about 100 lines and i need to edit about 10 of them.

Thank you very much for your help.

UPDATE:

Using the code posted by @J.F. Sebastian, i'm now getting the following error:

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

Line 611 of the file is:

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

So the problem is with the ' character.

If I comment out that line, the script is working fine with the code posted by @J.F. Sebastian.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

想你只要分分秒秒 2024-10-28 20:39:01
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
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()

Before:

ENABLEPRINTER=n 
PRINTERLIST=PRNT1, PRNT2  

PRNT1.PORT=9600 
PRNT1.BITS=8

After:

y=n 
PRNT3==PRNT1, PRNT2  

734=9600
PRNT1.BITS=8

Too simple to be definitive. Say what are the errors or weaknesses.

The advantage of regexes is they can be modulated easily to particular cases.

.

EDIT:

I've just seen that:

"what i want to do is assign a new value to the variable "

you could inform of that earlier !

Could you give an exemple of file before / after , please.

.

EDIT 2

Here's the code to change the values of certain variables in a file:

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)

Before:

ENABLEPRINTER=n 
PRINTERLIST=PRNT1, PRNT2  

PRNT1.PORT=9600 
PRNT1.BITS=8

After:

ENABLEPRINTER=y 
PRINTERLIST=PRNT3

PRNT1.PORT=8310 
PRNT1.BITS=8
旧伤还要旧人安 2024-10-28 20:39:01

如果文件位于 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'))

它不是很健壮,但有多种修复它可能会让后来的人受益。


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

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

要替换配置文件中的变量名称(使用 configobj 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< /code> 变量然后:

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

If the file is in java.util.Properties format then you could use 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'))

It is not very robust, but various fixes for it could benefit people who come next.


To replace multiple times in a short string:

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

To replace variables names in a configuration file (using configobj 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()

If by replace('ENABLEPRINTER', 'y') you mean assign y to the ENABLEPRINTER variable then:

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

It seems configobj is not compatible with:

name = '.'something

You could quote it:

name = "'.'something"

Or:

name = '.something'

Or

name = .something

conf.update() does something similar to:

for name, value in [('ENABLEPRINTER', 'y'), ('PRINTERLIST', 'PRNT3')]:
    conf[name] = value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文