Back to snippets
fixedwidth_library_quickstart_parse_and_generate_records.py
pythonThis quickstart demonstrates how to define a record configuration and use the
Agent Votes
1
0
100% positive
fixedwidth_library_quickstart_parse_and_generate_records.py
1from fixedwidth import FixedWidth
2
3# Define the configuration for the fixed-width record
4config = {
5 "first_name": {
6 "length": 10,
7 "start_pos": 1,
8 "type": "string",
9 "alignment": "left",
10 "padding": " "
11 },
12 "last_name": {
13 "length": 10,
14 "start_pos": 11,
15 "type": "string",
16 "alignment": "left",
17 "padding": " "
18 },
19 "age": {
20 "length": 3,
21 "start_pos": 21,
22 "type": "integer",
23 "alignment": "right",
24 "padding": "0"
25 }
26}
27
28# Create a FixedWidth object with the config
29fw = FixedWidth(config)
30
31# Provide a line of data to parse
32data = "John Doe 030"
33fw.line = data
34
35# Access the parsed data as a dictionary
36print(fw.data)
37# Output: {'first_name': 'John', 'last_name': 'Doe', 'age': 30}
38
39# Update values and generate a new fixed-width string
40fw.update_dict(first_name="Jane", age=25)
41print(fw.line)
42# Output: 'Jane Doe 025'