0

Input file Test.ini:

;INTEGRITY_PERIOD=300  
INTEGRITY_PERIOD=100

Code:

key = None
value = None

with open('hmi.ini', 'r') as inifile:
    for line in inifile:
        if line.startswith(';INTEGRITY_PERIOD='):
            continue;
        if line.startswith('INTEGRITY_PERIOD='):
            key, value = line.split("=")
            break

if value and value.isdigit():
    print(value)
else:
    print(300)

The above code is always returning 300. Looks like isdigit() is not working or is there anything wrong in my code ?

0

1 Answer 1

5

Your lines end in a line separator, which you did not remove. Strip the line to remove whitespace from the start and end:

key, value = line.strip().split("=")

A line separator (\n) is not a digit:

>>> '100\n'.isdigit()
False
>>> '100'.isdigit()
True

Rather than build your own parser, consider using the configparser module from the standard library. It fully supports the INI format (including using ; as a comment).

Sign up to request clarification or add additional context in comments.

3 Comments

When selecting the text in the provided code sample, it seems as though there are some spaces rather than a newline (though I'm not sure if this is just a formatting issue or not). When iterating over the lines, aren't newlines omitted automatically? Anyway, .strip() naturally handles any whitespace, be they spaces or newlines
@LennartKloppenburg: no, newlines are not omitted.
configparser module is really very useful. Thanks for letting me know about this library.

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.