How Can I Remove The White Characters From Configuration File?
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
Solution 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)
Solution 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!
Post a Comment for "How Can I Remove The White Characters From Configuration File?"