将单个位写入python中的文件 [英] write individual bits to a file in python
问题描述
python中是否有一种方法可以写入少于1个字节的数据 即使我写了以1位表示的数字0,文件大小也是1(8位)字节
is there a way in python to write less than 1 byte data even when I write the number 0 which represented in 1 bit the file size is 1(8 bits) byte
我尝试了struct模块
I tried the struct module
file.write(struct.pack('b',0))
数组模块
import array
data1=array.array('B')
x=bin(0)[2:]
data1.append(int(0,2))
f2=open('/root/x.txt','wb')
data1.tofile(f2)
推荐答案
不,您不能写少于一个字节的内容.字节是计算机可以处理的不可分割的内存量.硬件未配备来处理小于1个字节的数据单元(尽管字节的大小可能因机器而异).文件系统还以可能为4KB的块为单位处理数据,因此写入一位实际上会在磁盘上产生4KB的块.
No you cannot write less than a byte. A byte is an indivisble amount of memory the computer can handle. The hardware is not equipped to handle units of data <1 byte (though the size of a byte may differ from machine to machine). The file system also deals with data in units of blocks which may be 4KB, so writing one bit really results in a 4KB block on disk.
See also the more general version of this question: It is possible to write less than 1 byte to a file
这篇关于将单个位写入python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!