【问题标题】:Write decoded from base64 string to file将解码后的 base64 字符串写入文件
【发布时间】:2014-03-14 10:39:03
【问题描述】:

问题是如何将从base64解码的字符串写入文件?我使用下一段代码:

import base64

input_file = open('Input.txt', 'r')
coded_string = input_file.read()
decoded = base64.b64decode(coded_string)
output_file = open('Output.txt', 'w')
output_file.write(decoded)
output_file.close()

Input.txt 包含 base64 字符串(smth. like PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48cmV2aW)。脚本执行后,我想在 Output.txt 中看到 xml,但输出文件包含一些错误的符号(如 <?xml version="1.0" encoding="UTF-8"?><review-case create®vFFSТ#2)。同时,如果我没有从文件 Input.txt 中读取 base64 字符串,而是在脚本中将其指定为 coded_string = '''PD94bWwgdmVyc2lvbj0iMS4wIiBlbm...''',则 Output.txt 包含正确的 xml。这是utf编码有问题吗?如何解决这个问题?我在 Windows 7 上使用 Python2.7。提前致谢。

【问题讨论】:

  • 顺便说一句,它在我的 Ubuntu 上的行为方式相同。

标签: python base64


【解决方案1】:

你可能在 5 年后想出了这样做,但如果有人需要,这里就是解决方案。

import base64

with open('Input.txt', 'r') as input_file:
  coded_string = input_file.read()
decoded = base64.b64decode(coded_string)
with open('Output.txt', 'w', encoding="utf-8") as output_file:
  output_file.write(decoded.decode("utf-8"))

【讨论】:

  • 我没有时间忘记这个问题,但感谢您的回答
【解决方案2】:

在您使用“rb”而不是“r”打开的窗口下。

在您的情况下,您的代码应该是:

input_file = open('Input.txt', 'rb')

而不是

input_file = open('Input.txt', 'r')

顺便说一句: http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

在 Windows 上,附加到模式的 'b' 以二进制模式打开文件,因此还有 'rb'、'wb' 和 'r+b' 等模式。 Windows 上的 Python 区分了文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动稍作更改。这种对文件数据的幕后修改适用于 ASCII 文本文件,但它会破坏 JPEG 或 EXE 文件中的二进制数据。在读写此类文件时要非常小心使用二进制模式。在 Unix 上,将 'b' 附加到模式并没有什么坏处,因此您可以独立于平台使用它来处理所有二进制文件。

希望对你有帮助

【讨论】:

  • 谢谢。我试图使用rb 模式,但它似乎不是一个解决方案。结果保持不变。
猜你喜欢
  • 2014-06-22
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多