gpt4 book ai didi

python - 将二进制整数或字符串写入python中的文件

转载 作者:太空狗 更新时间:2023-10-29 19:36:00 25 4
gpt4 key购买 nike

我在 Python 中有一个字符串(它也可以是一个整数),我想将它写入一个文件。它只包含 ones 和 zeros 我希望将 ones 和 zeros 的模式写入文件。我想直接写二进制文件,因为我需要存储很多数据,但只是某些值。当我只需要三个时,我认为没有必要占用每个值使用八位的空间。

例如。假设我要将二进制字符串 "01100010" 写入文件。如果我在文本编辑器中打开它,它会显示 b(01100010 是 b 的 ascii 代码)。不过不要混淆。我不想写ascii码,例子只是说明我想直接写字节到文件。


澄清:

我的字符串看起来像这样:

binary_string = "001011010110000010010"

它不是由数字或字符的二进制代码组成的。它包含仅与我的程序相关的数据。

最佳答案

要写出字符串,您可以使用文件的 .write 方法。要写入整数,您需要使用 struct 模块

import struct

#...
with open('file.dat', 'wb') as f:
if isinstance(value, int):
f.write(struct.pack('i', value)) # write an int
elif isinstance(value, str):
f.write(value) # write a string
else:
raise TypeError('Can only write str or int')

但是int和string的表示方式不同,可以使用bin函数将其转为0和1组成的字符串

>>> bin(7)
'0b111'
>>> bin(7)[2:] #cut off the 0b
'111'

但也许处理所有这些 int 的最佳方法是为文件中的二进制字符串确定一个固定宽度,并像这样转换它们:

>>> x = 7
>>> '{0:032b}'.format(x) #32 character wide binary number with '0' as filler
'00000000000000000000000000000111'

关于python - 将二进制整数或字符串写入python中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com