Converting binary to base64 files in Python

in #stemgeeks6 months ago

Python is often conflated with text-based automation. Things like batch-processing of CSV files, JSON, and web-based stuff.

Really, though, it is a Swiss army knife of utility.

Even though it is interpreted, our desktop super computers are plenty beefy enough for Python to scream through tough tasks, and also the ease of use makes it useful for simple things too.

As an example, I needed to convert some binary files into Base64 encoded ascii for the web.

Of course the first thing I tried was a web search for an online tool, and those exist, but the format wasn't good, and worse I would have to manually use the tool slowly file by file.

Screen Shot 2021-03-29 at 12.54.11 PM.png
Python to the rescue.

Here's the script in selectable text that I wrote by copypasta Google searches - enjoy!

import sys
data = open(sys.argv[1], "rb").read()
encoded = base64.b64encode(data)
f = open(sys.argv[2], 'w+b')
byte_arr = encoded
binary_format = bytearray(byte_arr)