Search code examples
pythonfilebit

I need to read a file bit by bit in python


I would like an output like 01100011010... or [False,False,True,True,False,...] from a file to then create an encrypted file. I've already tried byte = file.read(1) but i don't know how to then convert it to bits.


Solution

  • You can read a file in binary mode this way:

    with open(r'path\to\file.ext', 'rb') as binary_file:
        bits = binary_file.read()
    

    The 'rb' option stands for Read Binary.


    For the output you asked for you can do something like this:

    [print(bit, end='') for bit in bits]
    

    that is the list comprehension equivalent to:

    for bit in bits:
        print(bit, end='')
    

    Since 'rb' gives you hex numbers instead of bin, you can use the built-in function bin to solve the problem:

    with open(r'D:\\help\help.txt', 'rb') as file:
        for char in file.read():
            print(bin(char), end='')