2

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)
user1604573
  • 175
  • 1
  • 2
  • 6
  • 1
    no. one byte is the minimum size of a non empty file. – mata Jul 08 '13 at 21:47
  • 2
    I'm leaving [this link to a question about huffman encoding](https://stackoverflow.com/questions/51425638/how-to-write-huffman-coding-to-a-file-using-python#51425774) here, as OP asks about it in a comment on the accepted answer and it is a good example of how you can better leverage only being able to write bytes. – MoxieBall Jul 19 '18 at 15:01

1 Answers1

3

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

Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • but how the Huffman encoding uses fewer bits to represent the most frequent symbols ?? – user1604573 Jul 08 '13 at 22:02
  • 3
    @user1604573 you can transmit a series of bits, or save a series of bits into a file if you want and then interperet them however you want, but you can't write less than one byte at a time. There's nothing stopping you from working bit-wise. If you wanted to store something like "hello" in huffman encoding, the bits would look like this: `1010000110011100100110`, broken into bytes `10100001` `10011100` `100110`. And you'd have two extra bits at the end. You can get around this by indicating how many bits to read, or how many characters are in your file with a number at the very beginning. – Ryan Haining Jul 08 '13 at 22:11