Skip to content
Advertisement

Python Configparser. Whitespace causes AttributeError

I recieve some files with .ini file with them. I have to recieve file names from [FILES] section.
Sometimes there is an extra witespace in another section of .ini-file which raises exception in ConfigParser module
The example of “bad” ini-file:

JavaScript

My code(Python 3.7):

JavaScript

I can’t influence on files I recieve so that is there any way to ignore this error? In fact I need only [FILES] section to parse.
Have tried empty_lines_in_values=False with no result
May be that’s invalid ini file and I should write my own parser?

Advertisement

Answer

If you only need the “FILES” part, a simple way is to:

  • open the file and read into a string
  • get the part after “[FILES]” using .split() method
  • add “[FILES]” before the string
  • use the configparser read_string method on the string

This is a hacky solution but it should work:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement