1

I am writing a program to read and write bits from a file to another file. I found a library called bitstring that helps to manipulate bits as strings. However, this library helps me to read bits, but I cannot write the read bits. Both inputs and outputs files have the same size, so it will be no problem in term of bytes. This is a part of my code.

import bitstring


file = bitstring.ConstBitStream(filename='paper.pdf')
print(file.length)

bits_to_read = 5000000
last_bits = 0

while file.pos < file.length-bits_to_read:
    bits = file.read(bits_to_read)
    str_bits = bitstring.BitArray(bits).bin



rest = file.length - file.pos
bits = file.read(rest)
str_bits = bitstring.BitArray(bits).bin

with kind of regards.

8
  • 1
    What do you mean "I cannot write the read bits". Show us which functions you tried, and what the result was? Did you open the second file in append or append-binary mode? Commented May 6, 2021 at 22:27
  • So, I'm reading bits from a file and do on them treatments, encryption. Next, I want to write the resulted bits into another file. The only solution I have is to write as bytes. but, I wanna do it like streaming bits. Commented May 8, 2021 at 9:34
  • There are 32 hits on [python] write bitstring, can you explain (in the question body, not here in comments) why what you want to do is different? Also, on SO you have to show what code you attempted, and any errors it gives. Commented May 8, 2021 at 9:51
  • @smci thx, just found a solution. Commented May 8, 2021 at 11:16
  • Does this answer your question? Write boolean string to binary file? Commented May 8, 2021 at 21:16

1 Answer 1

1

So, I have found a solution. I appended the resulted bits into one variable and next, I exported. This is a part of the code:

while file.pos < file.length-bits_to_read:
    bits = file.read(bits_to_read)
    str_bits = bitstring.BitArray(bits).bin
    encrypted_bits = ''.join(encrypt(str_bits, cipher))
    exported_str = exported_str + encrypted_bits

rest = file.length - file.pos
bits = file.read(rest)
str_bits = bitstring.BitArray(bits).bin
exported_str = exported_str + str_bits

exported_bits = bitstring.BitArray(bin=exported_str)
with open(output_name, 'wb') as f:
    f.write(exported_bits.tobytes())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.