如何在 Python 中编写整数,而不是整数字符串

RTC*_*222 0 python python-3.x

我需要创建 10,000 个随机整数的文件进行测试。我将在 Python 和 C 中使用该文件,因此我不能将数据表示为字符串,因为我不希望在 C 中产生整数转换的额外开销。

在 Python 中,我可以使用该方法struct.unpack将文件转换为整数,但无法使用该write()方法将其写入文件以在 C 中使用。

Python 有没有办法只将整数而不是整数作为字符串写入文件?我使用过print(val, file=f)and f.write(str(val)),但在这两种情况下它都会写入一个字符串。

这是我现在所在的位置:

file_root = "[ file root ]"

file_name = file_root + "Random_int64"

if os.path.exists(file_name):
    f = open(file_name, "wb")
    f.seek(0)

for _ in range(10000):
    val = random.randint(0, 10000)
    f.write(bytes(val))

f.close()
f = open(file_name, "rb")

wholefile = f.read()
struct.unpack(wholefile, I)
Run Code Online (Sandbox Code Playgroud)

我的unpack格式字符串错误,所以我现在正在处理。我对此不太熟悉struct.unpack

tde*_*ney 6

bytes(val),当val是 an时int,创建bytes指定长度的对象。如果你的随机数是 12345,那么你写的是 12345 个零,而不是数字。诀窍是打包然后写入每个整数。

结构模块字节顺序、大小和对齐部分中,“<”写入字节“小端”(Intel/AMD 使用的字节顺序)。下一个字符可以是“L”以写入 4 字节无符号长整数,或“Q”以写入 8 个字节。4 对于您的字符范围来说足够大,并且会生成较小的文件,但如果您将来想要更大的值,则 8 更“面向未来”。

假设您不希望随机数出现重复,您可以创建一个整数列表,将它们打乱,然后一一写入文件。确保打开二进制文件,以便不进行编码。

经过更多的清理,你会得到

import random
import struct

file_root = "testfile"
file_name = file_root + "Random_int64"

with open(file_name, "wb") as f:
    for _ in range(10000):
        f.write(struct.pack("<Q", random.randint(0, 10000)))
Run Code Online (Sandbox Code Playgroud)

您还可以使用bytearrayandpackinto首先构建缓冲区并写入一次。

import random
import struct

file_root = "testfile"
file_name = file_root + "Random_int64"

buf = bytearray(10000*8)
for offset in range(10000*8, 8):
    struct.pack_into(buf, "<Q", offset, random.randint(0, 10000))

with open(file_name, "wb") as f:
    f.write(buf)
Run Code Online (Sandbox Code Playgroud)

如果您不介意使用标准库之外的包,numpy 有经典的

import numpy as np
np.random.randint(10000, size=10000).tofile("test.bin")
Run Code Online (Sandbox Code Playgroud)

如果我们把赌注押在表现上,那就是我会去的地方。