write individual bits to a file in python

人走茶凉 提交于 2019-12-20 04:38:28

问题


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

I tried the struct module

file.write(struct.pack('b',0))

array module

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:


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



来源:https://stackoverflow.com/questions/17536411/write-individual-bits-to-a-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!