我怎样才能把配置文件中的白色字符?(How can I remove the white chara

2019-09-23 21:12发布

我想使用Python修改samba配置文件。 这是我的代码

from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read( '/etc/samba/smb.conf' )

for section in parser.sections():
    print section
    for name, value in parser.items( section ):
        print '  %s = %r' % ( name, value )

但配置文件中包含标签,是否有可能忽略的标签?

ConfigParser.ParsingError: File contains parsing errors: /etc/samba/smb.conf
    [line 38]: '\tworkgroup = WORKGROUP\n'

Answer 1:

尝试这个:

from StringIO import StringIO

data = StringIO('\n'.join(line.strip() for line in open('/etc/samba/smb.conf')))

parser = SafeConfigParser()
parser.readfp(data)
...

另一种方法(感谢@mgilson的想法):

class stripfile(file):
    def readline(self):
        return super(FileStripper, self).readline().strip()

parser = SafeConfigParser()
with stripfile('/path/to/file') as f:
    parser.readfp(f)


Answer 2:

我想创建一个小的代理类饲料解析器:

class FileStripper(object):
    def __init__(self,f):
        self.fileobj = open(f)
        self.data = ( x.strip() for x in self.fileobj )
    def readline(self):
        return next(self.data)
    def close(self):
        self.fileobj.close()

parser = SafeConfigParser()
f = FileStripper(yourconfigfile)
parser.readfp(f)
f.close()

你甚至可以做一个好一点(允许多个文件,当你与他们完成自动的关闭等):

class FileStripper(object):
    def __init__(self,*fnames):
        def _line_yielder(filenames):
            for fname in filenames:
                with open(fname) as f:
                     for line in f:
                         yield line.strip()
        self.data = _line_yielder(fnames)

    def readline(self):
        return next(self.data)

它可以像这样使用:

parser = SafeConfigParser()
parser.readfp( FileStripper(yourconfigfile1,yourconfigfile2) )
#parser.readfp( FileStripper(yourconfigfile) ) #this would work too
#No need to close anything :).  Horray Context managers!


文章来源: How can I remove the white characters from configuration file?