AnarKi
AnarKi

Reputation: 997

Reading a list under a section with ConfigParser

I'm trying to read from a file which has a section structured like this:

[some_section]
102.45
102.68
103.1
109.4

It basically has some values that are separated by an '\n'

Is there a way to read this ?

I already tried the following:

# ConfigParser(strict=Flase) the parser will allow for duplicates in a section or option 
# ConfigParser(allow_no_value=True) the parser will allow for settings without values
parser = ConfigParser(allow_no_value=True, strict=False)
parser = ConfigParser()
parser.read(file)
my_list = parser.options('some_section')

The problem is that the parser is skipping duplicate values, and I need to keep those.

Upvotes: 1

Views: 237

Answers (2)

YQ.Wang
YQ.Wang

Reputation: 1177

If your txt file looks like this:

[some_section]
102.45
102.68
103.1
109.4

You can try this:

def parse(File):
    sectionData = {}
    with open(File, 'r') as f:
        # fist line: section name
        line = f.readline()
        sectionName = line[1:-2]
        sectionData[sectionName] = []    
        while line:
            # read and drop '\n'
            line = f.readline()[:-1]
            # skip last ''
            if line == '':
                break
            sectionData[sectionName].append(line)
    return sectionData

result = parse('test.txt')
print(result)

You will get:

{'some_section': ['102.45', '102.68', '103.1', '109.4']}

Upvotes: 0

Kraego
Kraego

Reputation: 3892

It's skipping the values cause the config file is Key Value like (see Format Keys (properties) - https://en.wikipedia.org/wiki/INI_file) and you just have keys: see https://docs.python.org/3/library/configparser.html.

Something like

[some_section]
  Value1=100.2
  Value2=101.3

would work

Upvotes: 1

Related Questions