Skip to content
systemcoding.dev
Mainframe

Convert a file to code page 037 in Python with cp037

Encode text to EBCDIC code page 037 in Python 3.13 with the cp037 codec, and decode it back, with no mainframe needed.

1 min read
Summarize in AI

Python ships the standard EBCDIC code page 037 as the cp037 codec, so you can build or inspect mainframe test data on a laptop. Encode a string and print the bytes in hex to see what a COBOL program on z/OS 3.1 would receive.

ebcdic.pypython
text = "HELLO, WORLD"
data = text.encode("cp037")
print(data.hex().upper())
print(data.decode("cp037"))
Text
C8C5D3D3D66B40E6D6D9D3C4
HELLO, WORLD

Note X'6B' for the comma and X'40' for the space. To convert a whole file, open the input with its own encoding and the output with encoding="cp037" and newline="", so Python does not translate line endings into ASCII X'0A'. EBCDIC text on a mainframe is normally fixed-length records with no line terminators, so you also pad each line to the record length yourself, with X'40'.

The Python codecs documentation lists cp037 and the other IBM pages such as cp1047, which you should use instead when the data came from z/OS UNIX.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.