0

I want to add lines extracted from a file to a section , the line is not in the form of option=value, i use this program:

import configparser
f = open('inventory_file', 'r')
config = configparser.ConfigParser()
config.add_section('windows')
for line in f:
    if line[4] == '0':
        config.set('windows', line, 'None')

with open('example.cfg', 'w') as configfile:
    config.write(configfile)

inventory_file:

W00VL9959061
W01V09908960
W01V09907745
W01V09907746
W01V09908317
W01V09907748
W00VL9968055

i got this result in example.cfg:

[windows]
w01v09908960
 = None
w01v09907745
 = None
w01v09907746
 = None
w01v09908317
 = None
w01v09907748
 = None

i want something like this:

[windows]
w01v09908960
w01v09907745
w01v09907746
w01v09908317
w01v09907748

Any idea pls how i can modify my script to get the expected result

3
  • i tried it : i got this: cat example.cfg [windows] w01v09908960 = None w01v09907745 = None w01v09907746 = None w01v09908317 = None w01v09907748 = None i want to get a rid of = None Commented Dec 27, 2019 at 16:02
  • 1
    Don't use ConfigParser if you don't need a config file. Config files will have a parameter = value format; don't write a config file if you want an Ansible inventory file. Commented Dec 27, 2019 at 16:19
  • @JL.Alex Please edit the question if you want to add details. Comments don't support preformatted text. Commented Dec 27, 2019 at 16:59

2 Answers 2

1

Since Python 3.2 you can pass allow_no_value to the ConfigParser constructor (read this section of the manual) to allow keys without values. Then you can use config.set(section,key) to get what you want:

import configparser
f = open('inventory_file', 'r')
config = configparser.ConfigParser(allow_no_value=True)
config.add_section('windows')
for line in f:
  if line[4] == '0':
    config.set('windows', line.rstrip('\n'))

with open('example.cfg', 'w') as configfile:
  config.write(configfile)

The resulting file is:

[windows]
w01v09908960
w01v09907745
w01v09907746
w01v09908317
w01v09907748
Sign up to request clarification or add additional context in comments.

Comments

0

INI files have parameter-value pairs (*not always, it turns out. See Psi's answer), so what you're looking for is not an INI file.

In this case you can do it manually:

with open('inventory_file') as inv, open('example.cfg', 'w') as cfg:
    print('[windows]', file=cfg)
    for line in inv:
        if line[4] == '0':
            print(line, file=cfg, end='')

Output in example.cfg:

[windows]
W01V09908960
W01V09907745
W01V09907746
W01V09908317
W01V09907748

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.