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

2022-01-09 00:00:00 python file binary file-io

问题描述

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

I have a string (it could be an integer too) in Python and I want to write it to a file. It contains only ones and zeros I want that pattern of ones and zeros to be written to a file. I want to write the binary directly because I need to store a lot of data, but only certain values. I see no need to take up the space of using eight bit per value when I only need three.

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

For instance. Let's say I were to write the binary string "01100010" to a file. If I opened it in a text editor it would say b (01100010 is the ascii code for b). Do not be confused though. I do not want to write ascii codes, the example was just to indicate that I want to directly write bytes to the file.

澄清:

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

My string looks something like this:

binary_string = "001011010110000010010"

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

It is not made of of the binary codes for numbers or characters. It contains data relative only to my program.


解决方案

好吧,经过一番搜索,我找到了答案.我相信你们其他人根本不明白(这可能是我的错,因为我不得不编辑两次才能说清楚).我在这里找到了它.

Alright, after quite a bit more searching, I found an answer. I believe that the rest of you simply didn't understand (which was probably my fault, as I had to edit twice to make it clear). I found it here.

答案是将每条数据拆分,将它们转换为二进制整数,然后将它们放入二进制数组中.之后,您可以使用数组的 tofile() 方法写入文件.

The answer was to split up each piece of data, convert them into a binary integer then put them in a binary array. After that, you can use the array's tofile() method to write to a file.

from array import *

bin_array = array('B')

bin_array.append(int('011',2))
bin_array.append(int('010',2))
bin_array.append(int('110',2))

with file('binary.mydata', 'wb') as f:
    bin_array.tofile(f)

相关文章