简体   繁体   中英

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'

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM