1

I'm a noob in Python

Problem: Find and replace Keys(strings) in files

For this I'm using Python ConfigParser. But I want to read the whole config (.ini) file into dictionary at once regardless of sections.

  1. Is it possible?
  2. Is it OK to do so?

I don't want to read a single section at a time

dict(Config.items('Section'))

Don't want to traverse the sections

for each_section in conf.sections():
    for (each_key, each_val) in conf.items(each_section):
        print each_key
        print each_val

What other options am I left with?

------- Edit 1 -------

Config.ini

[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local

[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/

[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}

Below is the file which contains the keys that are to be repalced

my dir is home_dir
my lib dir is library_dir
python path is path
My pictures are placed at my_pictures
Ali
  • 7,810
  • 12
  • 42
  • 65
  • What is the input? Please add a sample of it? What exatly to you mean by 'tokens'? How are the replacements defined? –  Apr 29 '16 at 07:49

2 Answers2

0

If You are looking to have a dictionary that will have all the values in the configuration file as a key value pair irrespective of its section, I think you are going in the correct way

dict={}
for sec in config.sections():
    for item in config.items(sec):
        dict[item[0]]=item[1]
Strik3r
  • 1,052
  • 8
  • 15
0

I think you are limited to reading through the different sections to get different values for each option in a section.

dict_sectionValues = {}
for section in Config.sections():
    for option in Config.options(section):
        value = Config.get(section, option)
        dict_sectionValues[option] = value

I think it is a little less readable, but you could reduce to:

dict_sectionValues = {}
for section in Config.sections():
    for option in Config.options(section):
        dict_sectionValues[option] = Config.get(section, option)
L0ngSh0t
  • 361
  • 2
  • 9