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
x
9
1
[LETTER]
2
SUBJECT=some text
3
some text
4
and text with whitespace in the beggining
5
6
[FILES]
7
0=file1.txt
8
1=file2.doc
9
My code(Python 3.7):
JavaScript
1
23
23
1
import configparser
2
3
def get_files_from_ini_file(info_file):
4
ini = configparser.ConfigParser(allow_no_value=True)
5
ini.read(info_file) # ERROR is here
6
if ini.has_section("FILES"):
7
pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
8
return pocket_files
9
10
print(get_files_from_ini_file("D:\bad.ini"))
11
12
13
Traceback (most recent call last):
14
File "D:/test.py", line 10, in <module>
15
print(get_files_from_ini_file("D:\bad.ini"))
16
File "D:/test.py", line 5, in get_files_from_ini_file
17
ini.read(info_file) # ERROR
18
File "C:UsersapAppDataLocalProgramsPythonPython37-32libconfigparser.py", line 696, in read
19
self._read(fp, filename)
20
File "C:UsersapAppDataLocalProgramsPythonPython37-32libconfigparser.py", line 1054, in _read
21
cursect[optname].append(value)
22
AttributeError: 'NoneType' object has no attribute 'append'
23
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
1
15
15
1
import configparser
2
3
def get_files_from_ini_file(info_file):
4
with open(info_file, 'r') as file:
5
ini_string = file.read()
6
useful_part = "[FILES]" + ini_string.split("[FILES]")[-1]
7
8
ini = configparser.ConfigParser(allow_no_value=True)
9
ini.read_string(useful_part) # ERROR is here
10
if ini.has_section("FILES"):
11
pocket_files = [ini.get("FILES", i) for i in ini.options("FILES")]
12
return pocket_files
13
14
print(get_files_from_ini_file("D:\bad.ini"))
15