【问题标题】:Base64 Decode Text File To Bin File In Python在 Python 中 Base64 解码文本文件到 Bin 文件
【发布时间】:2020-09-07 16:15:00
【问题描述】:

我有一个文本文件,我想将其解码为二进制代码文件。

目前,我在 Windows 上使用 openssl 来执行此操作。 命令为:base64 -d input.txt output.bin

Python 的 base64 命令对此有何等价作用?

编辑:

input.txt内容:

India
USA
Africa
Europe

我的尝试:

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

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

错误:

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'

【问题讨论】:

  • 那么你应该在提问之前做一些研究
  • 贴出你试过的代码也报错
  • 您可以使用base64模块或binascii
  • 添加了@komatiraju032。

标签: python python-3.x binary base64 decode


【解决方案1】:

通过快速的 Google 搜索找到了 this 关于编码和解码 base64 字符串的文章。在 python 中这样做的一个好方法可能是:

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

【讨论】:

  • 看到你的编辑后,我想我的答案仍然是你要找的。我会研究如何在 Python 中使用 with open 正确打开和编辑文件。
  • 如果我的回答有帮助,请务必将其标记为正确答案!
  • 当然,我会这样做的。我正在我的代码上测试它。一旦我得到预期的输出,我会标记你的答案。
猜你喜欢
  • 2015-05-07
  • 2017-01-23
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多