问题
I would like to modify the samba configuration file using python. This is my code
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 )
but the configuration file contains tab, is there any possibility to ignore the tabs?
ConfigParser.ParsingError: File contains parsing errors: /etc/samba/smb.conf
[line 38]: '\tworkgroup = WORKGROUP\n'
回答1:
Try this:
from StringIO import StringIO
data = StringIO('\n'.join(line.strip() for line in open('/etc/samba/smb.conf')))
parser = SafeConfigParser()
parser.readfp(data)
...
Another way (thank @mgilson for idea):
class stripfile(file):
def readline(self):
return super(FileStripper, self).readline().strip()
parser = SafeConfigParser()
with stripfile('/path/to/file') as f:
parser.readfp(f)
回答2:
I would create a small proxy class to feed the parser:
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()
You might even be able to do a little better (allow for multiple files, automagically close when you're finished with them, etc):
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)
It can be used like this:
parser = SafeConfigParser()
parser.readfp( FileStripper(yourconfigfile1,yourconfigfile2) )
#parser.readfp( FileStripper(yourconfigfile) ) #this would work too
#No need to close anything :). Horray Context managers!
来源:https://stackoverflow.com/questions/12821946/how-can-i-remove-the-white-characters-from-configuration-file