Config files with different types

Zach Hobesh hobesh at gmail.com
Thu Jul 2 19:56:10 CEST 2009


Hi all,

I've written a function that reads a specifically formatted text file
and spits out a dictionary.  Here's an example:

config.txt:

Destination = C:/Destination
Overwrite = True


Here's my function that takes 1 argument (text file)

the_file = open(textfile,'r')
linelist = the_file.read().split('\n')
the_file.close()
configs = {}
for line in linelist:
       try:
              key,value = line.split('=')
              key.strip()
              value.strip()
              key.lower()
              value.lower()
              configs[key] = value

       except ValueError:
              break

so I call this on my config file, and then I can refer back to any
config in my script like this:

shutil.move(your_file,configs['destination'])

which I like because it's very clear and readable.

So this works great for simple text config files.  Here's how I want
to improve it:

I want to be able to look at the value and determine what type it
SHOULD be.  Right now, configs['overwrite'] = 'true' (a string) when
it might be more useful as a boolean.  Is there a quick way to do
this?  I'd also like to able to read '1' as an in, '1.0' as a float,
etc...

I remember once I saw a script that took a string and tried int(),
float() wrapped in a try except, but I was wondering if there was a
more direct way.

Thanks in advance,

Zach



More information about the Python-list mailing list