0

I have a python program 'gametree.py', I want to predefine some variables in 'gametree.conf' and import them into my python program.

I can import them fine if I name it anything.py but I don't want to name it *.py. It's a config file, I want to match it to the python program name with a .conf extension.

gametree.py & gametree.conf

Possible?

UncleBoarder
  • 1
  • 1
  • 1
  • [This answer](https://stackoverflow.com/a/4152986/2833032) might be what you're looking for. You can access the name of a script using the `__file__` variable. – Samba Jun 26 '14 at 20:52
  • I don't see how that works. I want to use the command 'import gametree.conf'... which doesn't work. 'import anything.py' would work but that's not what I want. :-) – UncleBoarder Jun 26 '14 at 21:35
  • Don't use `import`; Use `open` and read the file. Use something like JSON to save the config data. – dawg Jun 26 '14 at 22:27
  • I tried playing with 'open' first. It seems much more difficult to read individual variables. I have to parse it and then the data that is numeric (some strings) I have to convert to integers. It's a lot more work to use open than to just read in the variables. I appreciate the offer and you're right but my question stands. Is there any way to import a file that does NOT end with the extension .py? – UncleBoarder Jun 26 '14 at 22:46
  • See http://stackoverflow.com/questions/8225954/python-configuration-file-any-file-format-recommendation-ini-format-still-appr/8226090#8226090 – codeape Jun 27 '14 at 12:06

1 Answers1

1

Yes, you want the configparser module

this should get you going:

configexample.py

import configparser
# note that this is for python3. Some changes need to be made for python2

# create parser object and read config file
config = configparser.RawConfigParser()
config.read('myconfig.cfg')

# loop through. Here for instructional purposes we print, but you can 
# assign etc instead.
for section in config.sections():
    print(section)
    for option in config.options(section):
        text = '{} {}'.format(option, config.get(section,option))
        print(text)

The section in the code extracts the contents of the brackets []. Here is an example configuration file myconfig.cfg

[auth]
username= Petra
password= topsecret
[database]
server= 192.168.1.34
port= 143
file='thatfile.dat'
[Location]
language = English
timezone = UTC

For more details have a look at the documentation.

Addendum: Incase you are interested you can also use the json and shlex modules too.

Vidhya G
  • 2,250
  • 1
  • 25
  • 28