Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk5 min

How to Use a Configuration File in Python

Use Python’s configparser for INI files, tomllib for TOML on Python 3.11+, or json for JSON. Learn loading, defaults, typed values, overrides, writing, and troubleshooting.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in configparser for a sectioned INI-style configuration file, tomllib to read TOML on Python 3.11 and later, or json for JSON. For a simple settings file that your program may also update, configparser is a practical starting point. The right choice depends on the format you already have, whether your program must write settings, and whether people need to preserve comments.

Read an INI configuration file with configparser

Create a file such as settings.ini with named sections and key-value options:

[server]
host = localhost
port = 8080

Load it and convert values to the types your program expects:

import configparser

config = configparser.ConfigParser()
config.read("settings.ini", encoding="utf-8")

host = config["server"]["host"]
port = config["server"].getint("port", fallback=8080)

print(f"Connecting to {host}:{port}")

Save this as a Python file beside settings.ini and run it with Python. The configuration path is relative to the process’s current working directory, which may not be the same as the script’s directory when you launch it elsewhere. For a fixed project-relative path, build the path from the script location rather than relying on where the command was run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make required configuration fail loudly

ConfigParser.read() returns the names of files it successfully read and silently ignores files it cannot open. That is useful for optional configuration locations, but risky when the program cannot work without the file. Use read_file() when absence should be an error:

import configparser

config = configparser.ConfigParser()
with open("settings.ini", encoding="utf-8") as file:
    config.read_file(file)

host = config["server"]["host"]

Opening the file directly means a missing file raises FileNotFoundError; malformed INI content raises a parsing error rather than being silently accepted.

Choose the configuration format

Format Standard-library option Good fit Important limitation
INI-style configparser Sectioned settings that need built-in reading and writing Values are strings until converted; writing parsed settings does not retain original comments.
TOML tomllib TOML input and its typed values Available in the standard library from Python 3.11; parses but does not write.
JSON json JSON-shaped data or an existing JSON interface JSON does not support comments.

These capabilities and limitations are documented by the Python configparser documentation and the Python tomllib documentation. If a project already uses a format, retaining it is often simpler than translating it. If users edit the file and comments must survive updates, do not assume that parsing and rewriting it with configparser will preserve those comments.

Convert values and handle defaults

INI options are read as strings. Use typed getters for common values rather than relying on implicit conversion:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • section.getint("port") for integers.
  • section.getfloat("timeout") for floating-point numbers.
  • section.getboolean("enabled") for booleans.

These getters raise conversion errors if the configured text is not valid for the requested type. A fallback can provide a value when an option is absent, as in getint("port", fallback=8080); it does not make malformed text valid.

Put shared options in [DEFAULT] and section-specific options in their own section:

[DEFAULT]
timeout = 10

[server]
host = localhost
port = 8080

Options in [DEFAULT] are available through other sections unless overridden there. Option names are case-insensitive by default and are normalized to lowercase. If case-sensitive option names are necessary, configure optionxform accordingly before reading the file.

Layer files with explicit precedence

You can read several INI files into the same parser. Options in later files override conflicting values from earlier files, while earlier options that are not replaced remain. For example, use a base file and then an optional local override:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import configparser

config = configparser.ConfigParser()
config.read(
    ["settings.ini", "settings.local.ini"],
    encoding="utf-8",
)

host = config["server"]["host"]
port = config["server"].getint("port", fallback=8080)

Here, settings.local.ini wins for any duplicate option. Since read() ignores files it cannot open, this pattern treats both paths as optional. If the base file is required, load it with read_file() first, then use read() for optional overrides.

Understand interpolation before using it

ConfigParser enables interpolation by default, allowing values to refer to other values using its interpolation syntax. If literal percent signs or user-supplied text cause unexpected interpolation behavior, request a raw value with the getter’s raw=True option, or create the parser with interpolation disabled:

config = configparser.ConfigParser(interpolation=None)

Choose deliberately: disabling interpolation changes how references in the file are interpreted. Avoid placing secrets in configuration files that might be committed or shared; the format itself does not provide secret protection.

Read TOML with tomllib

Python 3.11 and later include tomllib in the standard library. It parses TOML 1.0.0 and is read-only. Open TOML in binary mode and pass the file object to load():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import tomllib

with open("settings.toml", "rb") as file:
    config = tomllib.load(file)

host = config["server"]["host"]
port = config["server"]["port"]

print(f"Connecting to {host}:{port}")

For example, settings.toml can contain:

[server]
host = "localhost"
port = 8080

TOML values are parsed into Python values, so the integer port is already an integer. If you need to write TOML or preserve formatting while editing it, tomllib alone is not enough; the Python documentation points to third-party packages for those tasks. Treat untrusted TOML as input that may consume substantial CPU or memory, and limit how much data your program accepts for parsing.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Write an INI configuration file

ConfigParser can write its current settings to a text file:

import configparser

config = configparser.ConfigParser()
config["server"] = {"host": "localhost", "port": "8080"}

with open("settings.ini", "w", encoding="utf-8") as file:
    config.write(file)

The values assigned to an INI parser are text, so store numeric settings as strings when writing and convert them when reading. Writing parsed settings does not preserve comments from the original configuration file.

Troubleshoot common configuration problems

  • The file appears to be ignored: read() skips files it cannot open. Check the working directory and path; use read_file() for required input.
  • A section or option lookup fails: Check the spelling and case of the section and option. Option names are case-insensitive by default, but section names should match the configuration.
  • A number or boolean fails to load: Confirm the file contains a value accepted by the corresponding typed getter. A fallback handles a missing option, not invalid text.
  • Percent signs or references behave unexpectedly: Review the parser’s default interpolation behavior; use raw=True for an individual raw read or disable interpolation when references are not wanted.
  • TOML import fails on an older Python: tomllib was added in Python 3.11. Check the Python version before importing it; for TOML on earlier versions, a standard-library-only route is unavailable.
  • Comments disappear after saving: ConfigParser.write() does not preserve comments from parsed input. Keep comments separately or use an appropriate third-party tool if preserving formatting is required.

Or skip the browser setup

If your task is capturing a webpage rather than loading application settings, ScreenshotNeo offers a one-request screenshot API:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for parameters. Cookie banners, newsletter popups, and chat widgets are removed before capture; bot checks, blank pages, failed loads, and cache hits are not billed. ScreenshotNeo also has an MCP server for AI agents, and its free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. Learn more at ScreenshotNeo, or sign up for free.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.