【问题标题】:Create file from bytes stored as string从存储为字符串的字节创建文件
【发布时间】:2016-05-28 13:31:18
【问题描述】:

我有一个用例,我从数据库中获取一个 blob,我必须将其转换为二进制文件。 Python 将其存储为字符串,尽管它实际上是字节。当我尝试以二进制形式编写时,出现类型错误,str 不被接受。

我编写了一些示例代码来重现变量的样子。我在其他语言中看到过此任务相当容易的示例代码。非常感谢使用 python 3 帮助解决这个问题。这可能是我遗漏的非常简单的事情,我无法在网上找到答案。

import binascii

f = open('test.xlsx', 'rb')
content = binascii.hexlify(f.read())
f.close

output = content.decode("utf-8")

#output2 = hex(int(output, 16))

f = open('temp', 'wb')
f.write(output) #TypeError: a bytes-like object is required, not 'str' 
f.close()

#Convert back to type bytes and recreate the file

【问题讨论】:

  • 试试f.write(bytes(output, 'utf-8'))
  • 尝试将字符串转换为字节数组,例如gg=bytearray(textstring,'latin-1'),然后写出来。
  • 不要binascii.hexlify输入文件中的数据。只需read() 并写下来。以二进制模式从文件中读取的数据已经是一个类似字节的对象。 hexlify 在 Python 3 中将其转换为 utf-8 字符串。

标签: python python-3.x byte


【解决方案1】:

你可以写:

f.write(bytearray(output,"utf-8"))

代替:

f.write(output) #TypeError: a bytes-like object is required, not 'str' 

解决问题。虽然这似乎不是最 Pythonic 的方式。

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 2014-01-04
    • 1970-01-01
    • 2022-11-07
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2017-06-19
    相关资源
    最近更新 更多