相关疑难解决方法(0)

如何在python 3中将二进制数据写入stdout?

在python 2.x中,我可以这样做:

import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
Run Code Online (Sandbox Code Playgroud)

然而,现在,我得到了一个TypeError: can't write bytes to text stream.我应该使用一些秘密编码吗?

python python-3.x

88
推荐指数
3
解决办法
4万
查看次数

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

我需要创建 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

python python-3.x

0
推荐指数
1
解决办法
126
查看次数

标签 统计

python ×2

python-3.x ×2