Use Configparser to Extract Values from an INI File in Python

In this short guide, you’ll see how to use configparser to extract values from an INI file.

To start, here is a simplified template that you may use:

import configparser

# Create a ConfigParser object
config = configparser.ConfigParser()

# Read the INI file
config.read("config.ini")

# Access the values
section_name = "SectionName"
option_name = "OptionName"

value = config.get(section_name, option_name)
print(value)

Example of using Configparser to Extract Values from an INI File

Create an INI file named config.ini:

[Fruits]
fruits_list = apple, banana, orange

[Numbers]
numbers_list = 1, 2, 3, 4, 5

Create a Python script that reads and prints the values from the provided INI file:

import configparser

# Create a ConfigParser object
config = configparser.ConfigParser()

# Read the INI file
config.read("config.ini")

# Access the values
fruits_list = config.get("Fruits", "fruits_list")
numbers_list = config.get("Numbers", "numbers_list")

# Split the comma-separated values into a list
fruits = [fruit for fruit in fruits_list.split(",")]
numbers = [int(number) for number in numbers_list.split(",")]

print("Fruits List: ", fruits)
print("Numbers List: ", numbers)

Make sure to save the config.ini file in the same directory as the Python script.

Run the script, and you’ll get the following results:

Fruits List:  ['apple', 'banana', 'orange']
Numbers List:  [1, 2, 3, 4, 5]