用python将二进制整数或字符串写入文件
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.
我在Python中有一个字符串(也可以是一个整数),我想把它写到一个文件中。它只包含1和0,我希望将1和0的模式写入文件。我想直接写二进制,因为我需要存储很多数据,但只存储某些值。我认为,当我只需要3位时,不需要占用每个值使用8位的空间。
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.
例如。假设我要将二进制字符串“01100010”写入一个文件。如果我用文本编辑器打开它,它会说b(01100010是b的ascii码)。我不想写ascii码,这个例子只是表示我想直接将字节写入文件。
Clarification:
澄清:
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.
它不是由数字或字符的二进制代码组成的。它只包含与我的程序相关的数据。
5 个解决方案
#1
8
To write out a string you can use the file's .write
method. To write an integer, you will need to use the struct
module
要写出一个字符串,可以使用文件的.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')
However, the representation of int and string are different, you may with to use the bin
function instead to turn it into a string of 0s and 1s
但是,int和string的表示是不同的,您可以使用bin函数而不是将它转换成一个0和1的字符串
>>> bin(7)
'0b111'
>>> bin(7)[2:] #cut off the 0b
'111'
but maybe the best way to handle all these int
s is to decide on a fixed width for the binary strings in the file and convert them like so:
但是,处理所有这些ints的最好方法可能是决定文件中的二进制字符串的固定宽度,并像这样转换它们:
>>> x = 7
>>> '{0:032b}'.format(x) #32 character wide binary number with '0' as filler
'00000000000000000000000000000111'
更多相关文章
- Python -在文本文件中添加日期戳
- 在读取和评估文件列表时加速Python eval。
- Python笔记(九):字符串操作
- python 处理csv文件的过程对换行符的处理
- python 产生随机数,随机字符串
- linux修改文件所属用户和组
- Linux的文件权限
- linux系统更改目录和文件的权限总结
- CentOS7.2 通过nfs设置共享文件夹