Config files with different types

Z

Zach Hobesh

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
 
L

Lawrence D'Oliveiro

Zach said:
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.

Typically the type should be what you expect, not what is given. For
example, it doesn't make sense for your configs["overwrite"] setting to be
"red", does it?

A reasonable solution might be to have a table of expected types for each
config item keyword, e.g.

configs_types = \
{
...
"overwrite" : lambda x : x[0] not in set("nNfF"),
...
}

Then you can just do something like

configs[keyword] = configs_types[keyword](configs[keyword])

with appropriate trapping of ValueError exceptions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top