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

时间:2016-04-01 17:32:56

标签: python c++ file-handling

我想写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()

size of myfile

2 个答案:

答案 0 :(得分:2)

以下代码使用每个字节的1字节二进制表示法写入9个8位无符号整数文件。

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创建二进制数据。

答案 1 :(得分:0)

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

fmt.format("%-12s %.03f", beerName[x], beerStrenghts[x]);
相关问题