Two-way fixed-width <--> Python dict converter

1.3 · maintenance · verified Sat Apr 11

The `fixedwidth` library provides a straightforward two-way converter for interacting with fixed-width data files or strings in Python. It facilitates easy serialization of Python dictionaries into fixed-width format and deserialization back into dictionaries, based on a user-defined configuration specification. Last updated in 2018 (v1.3), it has been used in production environments for several years and is considered stable, though not actively developed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a fixed-width specification using a configuration dictionary, then use the `FixedWidth` class to parse a fixed-width string into a Python dictionary and serialize a dictionary back into a fixed-width string.

from fixedwidth import FixedWidth

# Define the fixed-width specification
# A field must have a start_pos and either an end_pos or a length.
# If both end_pos and length are provided, they must not conflict.
# A field may not have a default value if it is required.
# Supported types: 'string', 'integer', 'decimal'.
config = {
    'name': {
        'start_pos': 0,
        'end_pos': 10,
        'type': 'string',
        'required': True,
        'alignment': 'left',
        'padding': ' ',
    },
    'age': {
        'start_pos': 10,
        'length': 3,
        'type': 'integer',
        'required': False,
        'alignment': 'right',
        'padding': '0',
    },
    'city': {
        'start_pos': 13,
        'length': 10,
        'type': 'string',
        'required': True,
        'alignment': 'left',
        'padding': ' ',
    },
}

# Create a FixedWidth instance
fixed_width_spec = FixedWidth(config)

# Example 1: Read from a fixed-width line
fixed_width_line_to_read = "John Doe  025New York   "
data_dict = fixed_width_spec.read(fixed_width_line_to_read)
print("Parsed data:", data_dict)
# Expected output: {'name': 'John Doe', 'age': 25, 'city': 'New York'}

# Example 2: Write to a fixed-width line
data_to_write = {'name': 'Jane Smith', 'age': 30, 'city': 'Los Angeles'}
fixed_width_line_written = fixed_width_spec.write(data_to_write)
print("Formatted line:", fixed_width_line_written)
# Expected output: "Jane Smith030Los Angeles "

view raw JSON →