2012-10-10 55 views
3

我想用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' 
+3

你可以'.strip()'字符串,它也會刪除標籤。 – eumiro

回答

5

試試這個:

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) 
+0

我也想過從'file'繼承,但是我總是猶豫不決,因爲文檔說你應該用'open'來構造'file'對象 - 但我從來不明白爲什麼。 – mgilson

+0

@mgilson,我想這是因爲這種方法不允許在我的'stripfile'中傳遞'StringIO'或其他文件類對象。如果你的類構造函數採取文件,而不是文件名,這將是可能的,它是如此的好。但對於日常工作來說,這不是什麼大問題。 – defuz

5

我想創建一個小的代理類飼料解析器:

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! 
+0

如果您使'readline'成爲一個生成器(帶有'yield'),則不必將整個文件加載到'self.data'中。 –

+0

@MikeDeSimone - 我製作了一個'self.data'生成器,所以我沒有閱讀整個文件。 – mgilson

+0

@Mike DeSimone:它沒有。 'self.data'是一個生成器。 – martineau