Config files with different types

MRAB python at mrabarnett.plus.com
Thu Jul 2 20:12:07 CEST 2009


Zach Hobesh wrote:
> 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')

You could use .splitlines() or iterate over the file itself.

> the_file.close()
> configs = {}
> for line in linelist:
>        try:
>               key,value = line.split('=')
>               key.strip()
>               value.strip()
>               key.lower()
>               value.lower()

Strings are immutable. These methods don't modify the strings, but
_return_ the result.

>               configs[key] = value
> 
>        except ValueError:
>               break
> 
'break' will leave the loop. Is this intentional?

> 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.
> 
The way you saw was the safe, and recommended, way.

When checking for Boolean you might want to ignore the case; something
like:

bool_dict = {"false": False, "true": True}
...
try:
     value = bool_dict[value.strip().lower()]
except ValueError:
     # Not a Boolean.
     ...



More information about the Python-list mailing list