configparser bug

Peter Otten __peter__ at web.de
Wed Jan 25 06:30:56 EST 2017


Christos Malliopoulos wrote:

> Hi,
> 
> I run Ubuntu 16.04 LTS in a VM using VMWare Workstation on a Windows 10
> host.
> apt show python-configparser shows 3.3.0r2-2
> On python 2.7.12 I use the following code:
> 
> import configparser as cfg
> root =
> u'/'.join(os.path.split(os.path.abspath('cfg.py'))[0].split('/')[:-2])
> cp = cfg.ConfigParser(interpolation = cfg.ExtendedInterpolation())
> cp.read(os.path.abspath(os.path.join(root, u'config/sampling.cfg')))

This looks confusing. Are you sure you are reading the right sampling.cfg?

> cp.items('Sampling')
> 
> sampling.cfg contains the following lines:
> [Sampling]
>     nobs = 10
>     nzin = 4
>     nzout = 3
>     ndrops = 1
> 
>     inh = day,loc,z0,value
>     outh = day,loc,sku,value
> 
>     invalran = 1,1e3
>     outvalran = 1,1000
> 
> cp.items(u'Sampling') prints the following:
> [(u'nobs', u'10'),
>  (u'nzin', u'4'),
>  (u'nzout', u'3\nndrops = 1'),
>  (u'inh', u'day,loc,z0,value'),
>  (u'outh', u'day,loc,sku,value'),
>  (u'invalran', u'1,1e3'),
>  (u'outvalran', u'1,1000')]
> 
> ndrops = 1 is not parsed correctly

It looks like the parser does not expand tabs, and your problem may be 
mixing tabs and spaces:

$ cat demo.py
import configparser

data = """\
[Sampling]
\talpha = 1
\tbeta = 2
 \tgamma = 3
\tdelta = 4
"""
print "what you see:"
print data.expandtabs(4)

print "what the parser sees:"
print data.replace("\t", " ")

with open("sampling.cfg", "w") as f:
    f.write(data)

cp = configparser.ConfigParser(
    interpolation=configparser.ExtendedInterpolation()
)
cp.read("sampling.cfg")
for item in cp.items('Sampling'):
    print item
$ python demo.py 
what you see:
[Sampling]
    alpha = 1
    beta = 2
    gamma = 3
    delta = 4

what the parser sees:
[Sampling]
 alpha = 1
 beta = 2
  gamma = 3
 delta = 4

(u'alpha', u'1')
(u'beta', u'2\ngamma = 3')
(u'delta', u'4')
$ 





More information about the Python-list mailing list