Bogota
Bogota

Reputation: 391

Base64 Decode Text File To Bin File In Python

I have a text file and I want to decode it to binary code file.

Currently, I'm using openssl on Windows to do this. The command is: base64 -d input.txt output.bin

What could be the equivalent Python's base64 command for this?

Edit:

input.txt Content:

India
USA
Africa
Europe

My try:

InputFile = open('input.txt', 'r')
InputFile_Content = InputFile.read()
print(InputFile_Content)

print(base64.decode(InputFile_Content, 'Output.bin'))

Error:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print(base64.decode(InputFile_Content, 'Output.bin'))
  File "Python\Python37\lib\base64.py", line 502, in decode
    line = input.readline()
AttributeError: 'str' object has no attribute 'readline'

Upvotes: 0

Views: 726

Answers (1)

Nythepegasus
Nythepegasus

Reputation: 46

A quick Google search brought up this article about encoding and decoding base64 strings. Probably a good way to do that in python is to do:

import base64

with open("input.txt", "r") as f:
    message = f.read().encode("ascii")

with open("output.bin", "wb") as f:
    f.write(base64.b64encode(message))

Upvotes: 1

Related Questions