如何在python中写入整数,特别是没有字节(文件写入)

muk*_*rma 3 python

假设我必须在文件中存储少量整数,如1024或512或10240或900000,但条件是我只能消耗4个字节(不少于也不是最大).但是在使用write方法编写python文件时,它存储为"1024"或"512"或"10240"即它们写为ascii值但我想直接存储它们的二进制值.

任何帮助都会非常明显.

Joh*_*ooy 12

使用struct模块

>>> import struct
>>> struct.pack("i",1024)
'\x00\x04\x00\x00'
>>> struct.pack("i",10240)
'\x00(\x00\x00'
>>> struct.pack("i",900000)
'\xa0\xbb\r\x00'
Run Code Online (Sandbox Code Playgroud)

在Python3中,您可以使用to_bytesint 的方法.1024左右的paren只需要1024.解析为float并导致语法错误.

>>> (1024).to_bytes(4, "big")
b'\x00\x00\x04\x00'
>>> (1024).to_bytes(4, "little")
b'\x00\x04\x00\x00'
Run Code Online (Sandbox Code Playgroud)