如何从文件中读取位?

时间:2012-05-21 17:28:08

标签: python io binary

我知道如何读取字节 - x.read(number_of_bytes),但我怎样才能读取Python中的位?

我必须从二进制文件

中只读取5位(不是8位[1字节])

任何想法或方法?

3 个答案:

答案 0 :(得分:29)

Python一次只能读取一个字节。您需要读取一个完整的字节,然后只需从该字节中提取所需的值,例如

b = x.read(1)
firstfivebits = b >> 3

或者如果你想要5个最低有效位,而不是5个最高有效位:

b = x.read(1)
lastfivebits = b & 0b11111

可在此处找到其他一些有用的位操作信息:http://wiki.python.org/moin/BitManipulation

答案 1 :(得分:4)

正如公认的答案所述,标准Python I / O一次只能读写整个字节。但是,您可以使用Bitwise I/O的此配方模拟这样的位流。

<强>更新

修改Rosetta Code的Python版本后,在Python 2&amp; 3,我将这些变化纳入了这个答案。

除此之外,后来,在受到@mhernandez发表的评论的启发后,我进一步修改了Rosetta代码,因此它支持所谓的context manager protocol,它允许使用它的两个类的实例在Python with语句中。最新版本如下所示:

class BitWriter(object):
    def __init__(self, f):
        self.accumulator = 0
        self.bcount = 0
        self.out = f

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.flush()

    def __del__(self):
        try:
            self.flush()
        except ValueError:   # I/O operation on closed file.
            pass

    def _writebit(self, bit):
        if self.bcount == 8:
            self.flush()
        if bit > 0:
            self.accumulator |= 1 << 7-self.bcount
        self.bcount += 1

    def writebits(self, bits, n):
        while n > 0:
            self._writebit(bits & 1 << n-1)
            n -= 1

    def flush(self):
        self.out.write(bytearray([self.accumulator]))
        self.accumulator = 0
        self.bcount = 0


class BitReader(object):
    def __init__(self, f):
        self.input = f
        self.accumulator = 0
        self.bcount = 0
        self.read = 0

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def _readbit(self):
        if not self.bcount:
            a = self.input.read(1)
            if a:
                self.accumulator = ord(a)
            self.bcount = 8
            self.read = len(a)
        rv = (self.accumulator & (1 << self.bcount-1)) >> self.bcount-1
        self.bcount -= 1
        return rv

    def readbits(self, n):
        v = 0
        while n > 0:
            v = (v << 1) | self._readbit()
            n -= 1
        return v

if __name__ == '__main__':
    import os
    import sys
    # Determine this module's name from it's file name and import it.
    module_name = os.path.splitext(os.path.basename(__file__))[0]
    bitio = __import__(module_name)

    with open('bitio_test.dat', 'wb') as outfile:
        with bitio.BitWriter(outfile) as writer:
            chars = '12345abcde'
            for ch in chars:
                writer.writebits(ord(ch), 7)

    with open('bitio_test.dat', 'rb') as infile:
        with bitio.BitReader(infile) as reader:
            chars = []
            while True:
                x = reader.readbits(7)
                if not reader.read:  # End-of-file?
                    break
                chars.append(chr(x))
            print(''.join(chars))

另一个用法示例,说明如何“压缩”8位字节ASCII流,丢弃最重要的“未使用”位...并将其读回(但不要将其用作上下文管理器)。

import sys
import bitio

o = bitio.BitWriter(sys.stdout)
c = sys.stdin.read(1)
while len(c) > 0:
    o.writebits(ord(c), 7)
    c = sys.stdin.read(1)
o.flush()

...并“解散”相同的流:

import sys
import bitio

r = bitio.BitReader(sys.stdin)
while True:
    x = r.readbits(7)
    if not r.read:  # nothing read
        break
    sys.stdout.write(chr(x))

答案 2 :(得分:0)

它出现在Google搜索的顶部,用于使用python读取位。

我发现bitstring是一个读取位的好软件包,也是对本机功能的改进(对Python 3.6来说还不错),例如

# import module
from bitstring import ConstBitStream

# read file
b = ConstBitStream(filename='file.bin')

# read 5 bits
output = b.read(5)

# convert to unsigned int
integer_value = output.uint

更多文档和详细信息在这里: https://pythonhosted.org/bitstring/index.html