Двоичные файлы, закодированные с помощью Base64, — это распространенный способ представления нетекстовых данных, таких как изображения или аудио, в виде последовательности символов ASCII. В этой статье блога мы рассмотрим различные методы Python для чтения и декодирования двоичного файла, закодированного с помощью Base64, а затем декодирования его как UTF-8.
Метод 1: использование модулей base64 и кодеков
import base64
import codecs
# Read the binary file
with open('binary_file.bin', 'rb') as file:
encoded_data = file.read()
# Decode Base64 and decode as UTF-8
decoded_data = base64.b64decode(encoded_data)
decoded_text = codecs.decode(decoded_data, 'utf-8')
# Print the decoded text
print(decoded_text)
Метод 2: использование кодировки base64 и встроенной кодировки utf-8
import base64
# Read the binary file
with open('binary_file.bin', 'rb') as file:
encoded_data = file.read()
# Decode Base64 and decode as UTF-8
decoded_data = base64.b64decode(encoded_data)
decoded_text = decoded_data.decode('utf-8')
# Print the decoded text
print(decoded_text)
Метод 3: использование модулей base64 и binascii
import base64
import binascii
# Read the binary file
with open('binary_file.bin', 'rb') as file:
encoded_data = file.read()
# Decode Base64 and decode as UTF-8
decoded_data = base64.b64decode(encoded_data)
decoded_text = binascii.hexlify(decoded_data).decode('utf-8')
# Print the decoded text
print(decoded_text)
Метод 4. Использование модулей base64 и io
import base64
import io
# Read the binary file
with open('binary_file.bin', 'rb') as file:
encoded_data = file.read()
# Decode Base64 and decode as UTF-8
decoded_data = base64.b64decode(encoded_data)
decoded_text = io.BytesIO(decoded_data).read().decode('utf-8')
# Print the decoded text
print(decoded_text)
Во всех вышеперечисленных методах мы сначала читаем двоичный файл, а затем используем функцию base64.b64decode()для декодирования данных в кодировке Base64. Наконец, мы декодируем полученные двоичные данные как UTF-8, чтобы получить читаемый текст.