0

I have a text file called sampl1.txt. This is what is inside this text file:-

111
112
113
114
115

I have a .ini file called config_num.ini which contains:-

[num_group]
file = sample1.txt

Here is the code snippet:-

import ConfigParser
config = ConfigParser.ConfigParser()

config.read('config_num.ini')
sample = config.get('num_group','file')
print sample

Is there any way to parse this so that when I read this 'file' and try to print it, it prints the elements which are in the txt file? Right now it prints sample1.txt. I want the numbers to printed.

user2963623
  • 2,267
  • 1
  • 14
  • 25
sam
  • 127
  • 3
  • 13

2 Answers2

3

You almost answered the question in itself!

import ConfigParser
config = ConfigParser.ConfigParser()

config.read('config_num.ini')
sample = config.get('num_group','file')
sample = open(sample, 'r').read()
print sample
user2963623
  • 2,267
  • 1
  • 14
  • 25
0

Well, you'd have to override your ConfigParser, but I'd advise only loading the file when you call get

from ConfigParser import ConfigParser

class MyConfigParser(ConfigParser):
    def get(self, section, option, **kwargs):
        ret = super(MyConfigParser, self).get(section, option, **kwargs)

        if option == "file":
            try:
                return open(ret, 'r').read()
            except IOError:
                pass

        return ret

Then you can create your new ConfigParser

cfg = MyConfigParser()
cfg.read('config_num.ini')
print cfg.get('num_group', 'file')
Chris Clarke
  • 2,103
  • 2
  • 14
  • 19