Monday, April 21, 2025
HomePythonPython 101 - An Intro to Working with INI recordsdata Utilizing configparser

Python 101 – An Intro to Working with INI recordsdata Utilizing configparser


Many applications require configuration. Most have a default configuration and plenty of enable the person to regulate that configuration. There are a lot of various kinds of configuration recordsdata. Some use textual content recordsdata whereas others use databases. Python has an ordinary library known as configparser that you should use to work with Microsoft Home windows INI recordsdata.

On this tutorial, you’ll cowl the next matters:

  • An instance INI file
  • Making a config file
  • Enhancing a config file
  • Studying a config file

By the top of this tutorial, it is possible for you to to make use of INI configuration recordsdata programmatically with Python.

Let’s get began!

Instance INI File

There are a lot of examples of INI recordsdata on the Web. Yow will discover one over within the Mypy documentation. Mypy is a well-liked kind checker for Python. Right here is the mypy.ini file that they use for instance:

# International choices:

[mypy]
warn_return_any = True
warn_unused_configs = True

# per-module choices:

[mypy-mycode.foo.*]
disallow_untyped_defs = True

[ypy-mycode.bar]
warn_return_any = False

[mypy-somelibrary]
ignore_missing_imports = True

Sections are denoted by being positioned inside sq. braces. Then, every part can have zero or extra settings. Within the subsequent part, you’ll learn to create this configuration file programmatically with Python.

Making a Config File

The documentation for Python’s configparsermodule is useful. They inform you the right way to recreate an instance INI file proper within the documentation. In fact, their instance will not be the Mypy instance above. Your job is slightly bit more durable as you want to have the ability to insert feedback into your configuration, which isn’t lined within the documentation. Don’t fear. You’ll learn to do this now!

Open up your Python editor and create a brand new file known as create_config.py. Then enter the next code:

# create_config.py

import configparser

config = configparser.ConfigParser(allow_no_value=True)

config["mypy"] = {"warn_return_any": "True",
                  "warn_unused_configs": "True",}
config.set("mypy", "n# Per-module choices:")

config["mypy-mycode.foo.*"] = {"disallow_untyped_defs": "True"}
config["ypy-mycode.bar"] = {"warn_return_any": "False"}
config["mypy-somelibrary"] = {"ignore_missing_imports": "True"}

with open("custom_mypy.ini", "w") as config_file:
    config_file.write("# International choices:nn")
    config.write(config_file)


The documentation states that the allow_no_value parameter permits for together with sections that would not have values. It’s essential add this to have the ability to add feedback in the course of a piece to be added as effectively. In any other case, you’re going to get a TypeError.

So as to add total sections, you employ a dictionary-like interface. Every part is denoted by the important thing, and that part’s values are added by setting that key to a different dictionary.

When you end creating every part and its contents, you may write the configuration file to disk. You open a file for writing, then write the primary remark. Subsequent, you employ the config.write() methodology to put in writing the remainder of the file.

Attempt operating the code above; you need to get the identical INI file because the one firstly of this text.

Enhancing a Config File

The configparserlibrary makes enhancing your configuration recordsdata largely painless. You’ll learn to change a setting within the config file and add a brand new part to your pre-existing configuration.

Create a brand new file named edit_config.py and add the next code to it:

# edit_config.py

import configparser

config = configparser.ConfigParser()
config.learn("custom_mypy.ini")

# Change an merchandise's worth
config.set("mypy-somelibrary", "ignore_missing_imports", "False")

# Add a brand new part
config["new-random-section"] = {"compressed": "True"}

with open("modified_mypy.ini", "w") as config_file:
    config.write(config_file)

On this case, after create the ConfigParser()occasion, you name learn()to learn the required configuration file. Then you may set any worth you need.

Sadly, you can’t use dictionary-like syntax to set values. As a substitute, you need to use set()which takes the next parameters:

  • part – The title of the part.
  • possibility – The choice you want to change.
  • worth – The brand new worth you wish to set.

Including a brand new part works prefer it did once you created the preliminary sections within the final code instance. You continue to use dictionary-like syntax the place the brand new part is the important thing and the worth is a dictionary of a number of settings to go in your part.

If you run this code, it’s going to create an INI file with the next contents:

[mypy]
warn_return_any = True
warn_unused_configs = True

[mypy-mycode.foo.*]
disallow_untyped_defs = True

[ypy-mycode.bar]
warn_return_any = False

[mypy-somelibrary]
ignore_missing_imports = False

[new-random-section]
compressed = True


Good job! You’ve simply discovered the right way to modify an INI file with Python!

Now you might be able to study studying INI recordsdata.

Studying a Config File

You already caught a glimpse of the right way to learn a configuration file within the earlier part. The first methodology is by calling the ConfigParser‘s learn()methodology.

Right here’s an instance utilizing the brand new INI file you simply created:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.learn(r"C:codemodified_mypy.ini")
['C:codemodified_mypy.ini']
>>> config["mypy"]
<Part: mypy>
>>> config["mypy"]["warn_return_any"]
'True'
>>> config["unknown"]
Traceback (most up-to-date name final):
  Python Shell, immediate 8, line 1
    config["unknown"]
  File "c:usersMikeappdatalocalprogramspythonpython312libconfigparser.py", line 941, in __getitem__
    increase KeyError(key)
builtins.KeyError: 'unknown'

You may entry particular person values utilizing dictionary syntax. Should you occur to attempt to entry a piece or an possibility that doesn’t exist, you’ll obtain a KeyError.

The configparser has a second studying methodology known as read_string() that you should use as effectively. Right here is an instance:

>>> sample_config = """
... [mypy]
... warn_return_any = True
... warn_unused_configs = True
... 
... # Per-module choices:
... 
... [mypy-mycode.foo.*]
... disallow_untyped_defs = True
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)
>>> config["mypy"]["warn_return_any"]
'True'

You employ read_string() to learn in a multiline string after which entry values within it. Fairly neat, eh?

You too can seize the part and them use listing comprehensions to extract the choices from every part:

>>> config.sections()
['mypy', 'mypy-mycode.foo.*']
>>> [option for option in config["mypy"]]
['warn_return_any', 'warn_unused_configs']

The code above is a helpful instance for getting on the configuration choices shortly and simply.

Wrapping Up

Having a option to configure your software makes it extra helpful and permits the person extra management over how their copy of the appliance works. On this article, you discovered how in regards to the following matters:

  • An instance INI file
  • Making a config file
  • Enhancing a config file
  • Studying a config file

The configparser library has extra options than what is roofed right here. For instance, you should use interpolation to preprocess values or customise the parser course of. Try the documentation for full particulars on these and different options.

Within the meantime, have enjoyable and revel in this neat characteristic of Python!

Associated Articles

You may additionally be eager about these associated articles:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments