简体   繁体   English

如何将 1 个字节写入二进制文件?

[英]How to write 1 byte to a binary file?

I'm trying to write just one byte to a file in Python.我正在尝试将一个字节写入 Python 中的文件。

i = 10
fh.write( six.int2byte(i) )

Will output '0x00 0x0a'将输出'0x00 0x0a'

fh.write( struct.pack('i', i) )

Will output '0x00 0x0a 0x00 0x00'将输出'0x00 0x0a 0x00 0x00'

I want to write a single byte with the value 10 to the file.我想将值为 10 的单个字节写入文件。

You can just build a bytes object with that value:您可以使用该值构建一个bytes对象:

with open('my_file', 'wb') as f:
    f.write(bytes([10]))

This works only in python3.这仅适用于 python3。 If you replace bytes with bytearray it works in both python2 and 3.如果你用bytearray替换bytes ,它在 python2 和 3 中都有效。

Also: remember to open the file in binary mode to write bytes to it.另外:记得以二进制模式打开文件以向其写入字节。

struct.pack("=b",i) (signed) and struct.pack("=B",i) (unsigned) pack an integer as a single byte which you can see in thedocs for struct . struct.pack("=b",i) (signed) 和struct.pack("=B",i) (unsigned) 将整数打包为单个字节,您可以在struct 的文档中看到。 ( "=" is for using standard size and ignoring alignment - just in case) so you can do "="用于使用标准尺寸并忽略对齐 - 以防万一)所以你可以这样做

import struct
i=10
with open('binfile', 'wb') as f:
    f.write(struct.pack("=B",i))
i=10
f=open('binfile', 'w', encoding='utf-8')
f.write(chr(i))
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM