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:

[LETTER]
SUBJECT=some text
some text
 and text with whitespace in the beggining 

[FILES]
0=file1.txt
1=file2.doc

My code(Python 3.7):

import configparser

def get_files_from_ini_file(info_file):
    ini = configparser.ConfigParser(allow_no_value=True)
    ini.read(info_file) # ERROR is here
    if ini.has_section("FILES"):
        pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
        return pocket_files

print(get_files_from_ini_file("D:\bad.ini"))


Traceback (most recent call last):
  File "D:/test.py", line 10, in <module>
    print(get_files_from_ini_file("D:\bad.ini"))
  File "D:/test.py", line 5, in get_files_from_ini_file
    ini.read(info_file) # ERROR
  File "C:UsersapAppDataLocalProgramsPythonPython37-32libconfigparser.py", line 696, in read
    self._read(fp, filename)
  File "C:UsersapAppDataLocalProgramsPythonPython37-32libconfigparser.py", line 1054, in _read
    cursect[optname].append(value)
AttributeError: 'NoneType' object has no attribute 'append'

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:

  import configparser

  def get_files_from_ini_file(info_file):
      with open(info_file, 'r') as file:
          ini_string = file.read()
      useful_part = "[FILES]" + ini_string.split("[FILES]")[-1]

      ini = configparser.ConfigParser(allow_no_value=True)
      ini.read_string(useful_part) # ERROR is here
      if ini.has_section("FILES"):
          pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
          return pocket_files

  print(get_files_from_ini_file("D:\bad.ini"))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement