如何使用 python 将 8 位无符号整数写入文件?

How to write 8 bit unsigned integer to a file using python?

我想将 8 位无符号整数写入文件。在 C++ 中,我们可以使用 fprintf 来实现,格式为:

%[标志][宽度][.精度][长度]说明符

有什么方法可以使用 python 来实现吗? 我尝试通过分配 x =1 的值来仅打印 9 个整数值来查找文件的大小,我不明白文件大小是 35 字节。

f = open('myfile','w')
while x>0:
for i in range(0,9):
    a[i] = random.randint(0,255)
    f.write("%d" % a[i])
    f.write(" ")
f.write('\n')
x = x-1
f.close()

以下代码将九个 8 位无符号整数写入一个文件,使用每个字 1 个字节的二进制表示形式。

import struct
import random

f = open('myfile','wb')
for i in range(0,9):
    a = random.randint(0,255)
    f.write(struct.pack("=B", a))
f.close()

该程序的重​​要特点是:

  • 它使用模式 'wb',而不是 'w' 打开输出文件。

  • 它使用struct.pack创建二进制数据。

您需要以二进制方式打开文件,并将无符号整数值转换为一个字符串。这是一个简单的方法:

import random

with open('myfile', 'wb') as f:
    for _ in range(0, 9):
        a = random.randint(0, 255)
        f.write(chr(a))