Keywords: Python | configuration files | properties parsing | configparser | custom parser
Abstract: This paper provides an in-depth analysis of core methods for handling .properties format configuration files in Python's standard library. Based on the official implementation of the configparser module, it details the similarities and differences with Java's Properties class, including the mandatory section header requirement. A complete custom parser implementation is presented, supporting key-value pair separation, comment ignoring, and quotation handling. Through comparative analysis of multiple solutions' applicable scenarios, practical guidance is offered for configuration needs of varying complexity.
Standard Library Solution
In Python 2.x's standard library, the configparser module provides functionality closest to Java's Properties class. This module is specifically designed for parsing configuration files in INI-like formats, with basic syntax highly compatible with .properties files.
The key difference is that configparser requires configuration files to include section headers. For standard .properties files, a default section header must be added for proper parsing:
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('config.properties')
db_name = config.get('DatabaseSection', 'database.dbname')
user_name = config.get('DatabaseSection', 'database.user')
The corresponding configuration file needs to be modified as:
[DatabaseSection]
database.dbname=unitTest
database.user=root
database.password=secret
Custom Parser Implementation
When full compatibility with standard .properties format is required, a custom parsing function can be implemented. The following implementation supports equal signs or colons as separators and automatically ignores comment lines:
def load_properties(filepath, sep='=', comment_char='#'):
"""
Read .properties format configuration files
:param filepath: file path
:param sep: key-value separator, defaults to '='
:param comment_char: comment identifier, defaults to '#'
:return: dictionary containing configuration items
"""
props = {}
with open(filepath, "rt") as f:
for line in f:
line = line.strip()
if line and not line.startswith(comment_char):
key_value = line.split(sep, 1) # Split only at first separator
if len(key_value) == 2:
key = key_value[0].strip()
value = key_value[1].strip()
# Remove quotes from value ends
if (value.startswith('"') and value.endswith('"')) or \
(value.startswith("'") and value.endswith("'")):
value = value[1:-1]
props[key] = value
return props
# Usage example
config = load_properties('app.properties')
print(config.get('server.url'))
print(config.get('database.port'))
This implementation properly handles values containing special characters:
# Configuration file example
server.url = "http://example.com/api"
max.retries = 3
timeout.ms = 5000
# Comment line ignored
feature.enabled = true
Alternative Approaches Comparison
Python Module Import Method: Rename .properties files to .py files for direct import. This approach is simple but poses security risks and requires file content to comply with Python syntax specifications.
# Rename config.properties to config.py
# File content:
database_host = "localhost"
database_port = 5432
# Direct usage in code
import config
print(config.database_host)
Simple Parsing Method: Suitable for simplest key-value pair formats but doesn't support comments and complex value processing:
with open("simple.properties") as f:
config_dict = {}
for line in f:
if '=' in line:
key, value = line.split('=', 1)
config_dict[key.strip()] = value.strip()
Practical Recommendations
For projects requiring configuration compatibility with Java systems, custom parser implementation is recommended. This method provides maximum flexibility, handling various edge cases including values containing separators and quoted strings.
For new Python projects, directly using the configparser module with standard INI file format is advised. This format enjoys widespread support in the Python ecosystem and offers better readability and maintainability.
When selecting an approach, consider configuration file complexity, cross-language compatibility requirements, and team technology stack preferences. For simple configuration needs, custom parsers offer the best balance; for complex multi-section configurations, configparser is the more appropriate choice.