You can read and write INI files with the standard Python library configparser. https://docs.python.org/ja/3/library/configparser.html
An INI file is a file format that is sometimes used for configuration files, etc., which consists of sections, keys, and values. https://ja.wikipedia.org/wiki/INI%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB
By default, configparser is case insensitive for keys.
import configparser
ini_filename = "sample.ini"
"""Contents of INI file
[General]
Name = hogehoge
"""
parser = configparser.ConfigParser()
parser.read(ini_filename)
"""uppercase letter/Lowercase/Can be read regardless of mixing"""
assert parser["General"]["Name"] == "hogehoge", "Mixed"
assert parser["General"]["name"] == "hogehoge", "Lowercase"
assert parser["General"]["NAME"] == "hogehoge", "uppercase letter"
This works for both reading and writing INI files.
The sidecar file used in the software called RawTherapee has the contents like an INI file, I wanted to edit this all at once, but RawTherapee's sidecar file is case sensitive for key names. Therefore, if you edit / save as it is with the ConfigParser class, the key name will be all lowercase. There was a problem that RawTherapee could not be read properly.
This can be solved by setting the appropriate function in .optionxform
of the ConfigParser instance.
For the key name when reading and writing, the result converted by the ʻoptionxform` function is used.
Therefore, if you set ʻoptionxform` as follows, you can save the INI file while preserving the key name.
parser = configparser.ConfigParser()
parser.optionxform = str
parser.read(ini_filename)
parser["General"]["Name"] = "test"
with open(ini_filename, "w") as fp:
parser.write(fp)
Recommended Posts