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

标签 python file file-io binary

我在 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/

相关文章:

javascript - 文件阅读器不起作用?

python - 如何有效地从 numpy 数组中每行输出 n 项

python - 轨道发射问题 : "ConfigParser.NoSectionError: No section: ' formatters' "

python - Python中为多个变量添加多个返回值

python - 返回已排序单词的列表

javascript - css 隐藏 "Choose File"按钮但在选择后显示文件

python - Python中列表理解中的闭包

c - 如何在C中编辑特定的二进制数据而不删除/覆盖整个文件?

Python 错误 "IOError: [Errno 2] No such file or directory"但文件在那里

c - 将文本添加到行尾