【问题标题】:Write binary data to file in python3在python3中将二进制数据写入文件
【发布时间】:2013-11-21 19:34:45
【问题描述】:

我在这方面遇到了很多麻烦,其他问题似乎不是我要找的。所以基本上我有一个从

获得的字节列表
bytes = struct.pack('I',4)
bList = list(bytes)
# bList ends up being [0,0,0,4]
# Perform some operation that switches position of bytes in list, etc

所以现在我想把它写到一个文件中

f = open('/path/to/file','wb')
for i in range(0,len(bList)):
   f.write(bList[i])

但我不断收到错误

TypeError: 'int' does not support the buffer interface

我也试过写:

bytes(bList[i]) # Seems to write the incorrect number. 
str(bList[i]).encode()   # Seems to just write the string value instead of byte

【问题讨论】:

    标签: python-3.x bytearray binaryfiles


    【解决方案1】:

    哦,天哪,我不得不跳槽来解决这个问题。所以基本上我不得不这样做

    bList = bytes()
    bList += struct.pack('I',4)
    
    # Perform whatever byte operations I need to
    
    byteList = []
    
    # I know, there's probably a list comprehension to do this more elegantly
    for i in range(0,len(bList)):
        byteList.append(bList[i])
    
    f.write(bytes(byteList))
    

    因此 bytes 可以采用字节值数组(即使它们在数组中以十进制形式表示)并通过强制转换将其转换为适当的 byteArray

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      • 2014-10-05
      相关资源
      最近更新 更多