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:
fromStringIO importStringIO
data = StringIO('\n'.join(line.strip() for line inopen('/etc/samba/smb.conf')))
parser = SafeConfigParser()
parser.readfp(data)
...
Another way (thank @mgilson for idea):
classstripfile(file):
defreadline(self):
returnsuper(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:
classFileStripper(object):def__init__(self,f):
self.fileobj = open(f)
self.data = ( x.strip() for x inself.fileobj )
defreadline(self):
returnnext(self.data)
defclose(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):
classFileStripper(object):
def__init__(self,*fnames):
def_line_yielder(filenames):
for fname in filenames:
withopen(fname) as f:
for line in f:
yield line.strip()
self.data = _line_yielder(fnames)
defreadline(self):
returnnext(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?"