Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

write individual bits to a file in python

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...