Free tools Windows power users keep installed

One-click scans. No signup required.

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

Use Python’s standard-library configparser module to read INI-style settings, convert values to the types your code needs, and write changes back to a file. For example, a configuration can keep application settings together under a named section:

[DEFAULT]
log_level = INFO

[database]
host = localhost
port = 5432
use_tls = yes

This guide shows how to load required and optional files, retrieve and update settings, and avoid surprises with defaults, interpolation, duplicate options, and serialization.

How to read a configuration file in Python

configparser is included in Python’s standard library; there is nothing to install. Its ConfigParser class reads and writes section-based configuration files with a structure similar to Windows INI files. The official reference is the Python 3.15.0rc3 configparser documentation.

Save the example configuration as app.ini, then use read_file() when that file is required:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import configparser

config = configparser.ConfigParser()

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

host = config["database"]["host"]
print(host)

Opening the file explicitly makes a missing or unreadable required file an error your application can handle. By contrast, read() is designed for optional configuration paths: it ignores files it cannot open and returns the filenames it successfully parsed.

import configparser

config = configparser.ConfigParser()
loaded = config.read(["app.ini", "app.local.ini"], encoding="utf-8")
print("Loaded:", loaded)

When multiple files are read into the same parser, later files override conflicting settings, while settings present only in earlier files remain available. This is useful for layering a base configuration with local overrides.

How to retrieve and convert settings

Values read from a configuration file are strings. Retrieve them with mapping syntax or get(); use a typed getter when the application needs a number or boolean.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
database = config["database"]
host = database["host"]
port = config.getint("database", "port")
use_tls = config.getboolean("database", "use_tls")

print(host, port, use_tls)

The parser provides getint(), getfloat(), and getboolean(). A missing section or option normally raises an error. If absence is expected, provide a fallback:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
timeout = config.getint("database", "timeout", fallback=30)

For application-specific types, define a converter when constructing the parser; this makes a corresponding typed getter available:

config = configparser.ConfigParser(converters={"list": lambda value: value.split(",")})

With that converter, config.getlist("section", "option") returns the comma-separated value as a list. Validate the converted value separately if the application requires constraints such as an allowed range; ConfigParser is a parser, not a complete application schema validator.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Understand DEFAULT values and interpolation

Options in [DEFAULT] are inherited when accessed through other sections. In the example, config["database"]["log_level"] resolves to INFO. The default section supplies values; its options do not become ordinary named sections.

Basic interpolation is enabled by default. A value can refer to another option in the same section or a default, using %(name)s syntax:

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.
[DEFAULT]
root = /srv/app

[logs]
path = %(root)s/logs

To retrieve a value without expanding references for one call, use raw=True. A literal percent sign in an interpolated value must be escaped as %%.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
path_template = config.get("logs", "path", raw=True)

For a parser that should never interpolate, pass interpolation=None. If you prefer references such as ${section:option}, use ExtendedInterpolation.

config = configparser.ConfigParser(interpolation=None)

# Or, for ${section:option} references:
extended = configparser.ConfigParser(
    interpolation=configparser.ExtendedInterpolation()
)

How to change a setting and write the file

Assign string values to an existing section, then write the parser to a text-mode file object. Add the section first if it does not already exist.

section = "database"
if not config.has_section(section):
    config.add_section(section)

config.set(section, "host", "db.example.net")
config.set(section, "port", "5433")

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

write() serializes the parser’s current representation. It is intended to be readable again, but it does not preserve every original formatting detail or the layout of comments in the source file. In Python 3.14 and later, InvalidWriteError was added for representations that cannot be accurately read back; behavior and available features can therefore depend on the Python version in use.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right parser behavior

Required files or optional overrides

  • Use read_file() with an opened text file when the configuration must exist; catch file and parse errors at the point your application can report or recover from them.
  • Use read() for optional paths or layered configuration. Check its returned filenames if you need to know which files were loaded.

Duplicate options and sections

strict=True is the default. It rejects duplicate options or sections within one input source, such as a single file, string, or dictionary. Do not rely on a repeated setting in one file silently replacing the earlier value. Layering separate files with read() is different: later files can override earlier ones.

Option names and comments

Option names are converted to lowercase by default. If your format requires case-sensitive option names, customize optionxform() deliberately and ensure the rest of your application expects that behavior. Inline comment prefixes are not enabled by default; enabling them can make those characters unavailable as literal value content. Multiline values depend on indentation and the empty_lines_in_values setting.

Python version-sensitive features

Check the Python version you support before using newer parser options or relying on newer errors. Python 3.13 added allow_unnamed_section and a MultilineContinuationError case. Python 3.14 added InvalidWriteError for unsafe serialization. These are not available across all earlier Python releases.

Troubleshoot common ConfigParser errors

  • A required file appears to load as empty: read() silently skips paths it cannot open. Use read_file() for required input, or inspect the list returned by read().
  • NoSectionError or NoOptionError: verify spelling and section membership, remembering option names are lowercased by default. Use fallback= only when a missing value is an expected case.
  • DuplicateSectionError or DuplicateOptionError: remove the duplicate from that input source or restructure configuration into separate files if layering is intended. Do not turn off strict checking merely to conceal an ambiguous file.
  • InterpolationMissingOptionError or a literal percent problem: verify the referenced option exists in scope, use raw=True to read an unexpanded value, disable interpolation for the parser, or escape literal percent characters as %%.
  • A typed getter fails: confirm the text is valid for the requested conversion; for booleans, use accepted boolean spellings such as yes, no, true, false, on, off, 1, or 0.

Performance and safe input handling

For ordinary application configuration, the key practical reliability choice is explicit file handling: distinguish optional paths from required ones, and handle parsing failures rather than assuming every input is valid. Do not parse unbounded INI text from an untrusted source casually. The Python reference warns that parsing can consume excessive CPU and memory; impose an input-size limit before parsing data supplied by users or remote systems.

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

Or skip the browser setup

If your work also needs website screenshots, ScreenshotNeo is a screenshot API and MCP server for developers. One GET request can return a PNG, JPEG, WebP, or PDF; it removes cookie banners, popups, and chat widgets before capture, and bot checks, blank pages, and failed loads are never billed. AI agents can use its MCP server, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

For example, using cURL:

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 documentation for setup details. Sign up for the free plan.

Frequently Asked Questions

Can ConfigParser read JSON or TOML files?

No. It parses INI-like section and option syntax. Python’s standard library also provides tomllib for TOML files.

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.

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