Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何解决TypeError:“str”不支持缓冲区接口?_Python - Fatal编程技术网

Python 如何解决TypeError:“str”不支持缓冲区接口?

Python 如何解决TypeError:“str”不支持缓冲区接口?,python,Python,我的代码: big_int = 536870912 f = open('sample.txt', 'wb') for item in range(0, 10): y = bytearray.fromhex('{:0192x}'.format(big_int)) f.write("%s" %y) f.close() 我想把长整数转换成字节。但是我得到了TypeError:“str”不支持缓冲区接口 在Python 3中,字符串是隐式Unicode的,因此与特定的二进制表示分离,这取

我的代码:

big_int = 536870912
f = open('sample.txt', 'wb')

for item in range(0, 10):
   y = bytearray.fromhex('{:0192x}'.format(big_int))
   f.write("%s" %y)
f.close()

我想把长整数转换成字节。但是我得到了TypeError:“str”不支持缓冲区接口

在Python 3中,字符串是隐式Unicode的,因此与特定的二进制表示分离,这取决于所使用的编码。因此,字符串%s%y无法写入以二进制模式打开的文件

相反,您可以直接将y写入文件:

y = bytearray.fromhex('{:0192x}'.format(big_int))
f.write(y)
此外,您的代码%s%y实际上创建了一个Unicode字符串,其中包含y的字符串表示形式,即stry,这不是您所认为的。例如:

>>> '%s' % bytearray()
"bytearray(b'')"

在Python3中,字符串是隐式Unicode的,因此与特定的二进制表示分离,这取决于所使用的编码。因此,字符串%s%y无法写入以二进制模式打开的文件

相反,您可以直接将y写入文件:

y = bytearray.fromhex('{:0192x}'.format(big_int))
f.write(y)
此外,您的代码%s%y实际上创建了一个Unicode字符串,其中包含y的字符串表示形式,即stry,这不是您所认为的。例如:

>>> '%s' % bytearray()
"bytearray(b'')"

除了@Will answer之外,最好使用中的语句打开文件。此外,如果您使用Python3.2及更高版本,则可以使用或来反转该过程

我所说的例子:

big_int=536870912

with open('sample.txt', 'wb') as f:
    y = big_int.to_bytes((big_int.bit_length() // 8) + 1, byteorder='big')
    f.write(y)
    print(int.from_bytes(y, byteorder='big'))

最后一次打印是向您展示如何将其反转。

除了@Will answer之外,最好使用中的语句打开您的文件。此外,如果您使用Python3.2及更高版本,则可以使用或来反转该过程

我所说的例子:

big_int=536870912

with open('sample.txt', 'wb') as f:
    y = big_int.to_bytes((big_int.bit_length() // 8) + 1, byteorder='big')
    f.write(y)
    print(int.from_bytes(y, byteorder='big'))
最后一次打印是向您展示如何将其反转。

只需尝试执行f.writey只需尝试执行f.writey只需添加:使用更好的原因是,当作用域结束时,它会自动关闭文件,即使在中间出现异常时,也要添加:为什么As更好是因为在结束时自动关闭文件,即使在中间引发异常。