1

I am trying to write a pit array to a file in python as in this example: python bitarray to and from file

however, I get garbage in my actual test file:

test_1 = ^@^@
test_2 = ^@^@

code:

from bitarray import bitarray

def test_function(myBitArray):
    test_bitarray=bitarray(10)
    test_bitarray.setall(0)

    with open('test_file.inp','w') as output_file:
        output_file.write('test_1 = ')
        myBitArray.tofile(output_file)
        output_file.write('\ntest_2 = ')
        test_bitarray.tofile(output_file)

Any help with what's going wrong would be appreciated.

3
  • 1
    Are you on Windows? If so, set the file mode to wb. Commented Aug 5, 2013 at 23:23
  • what happens if you print bitarray before writing it Commented Aug 5, 2013 at 23:24
  • 1
    @JoranBeasley: That's just going to print <class 'bitarray.bitarray'>. Presumably you wanted to print test_bitarray, yes? That will print bitarray('0000000000'). Commented Aug 5, 2013 at 23:30

1 Answer 1

4

That's not garbage. The tofile function writes binary data to a binary file. A 10-bit-long bitarray with all 0's will be output as two bytes of 0. (The docs explain that when the length is not a multiple of 8, it's padded with 0 bits.) When you read that as text, two 0 bytes will look like ^@^@, because ^@ is the way (many) programs represent a 0 byte as text.

If you want a human-readable text-friendly representation, use the to01 method, which returns a human-readable strings. For example:

with open('test_file.inp','w') as output_file:
    output_file.write('test_1 = ')
    output_file.write(myBitArray.to01())
    output_file.write('\ntest_2 = ')
    output_file(test_bitarray.to01())

Or maybe you want this instead:

output_file(str(test_bitarray))

… which will give you something like:

bitarray('0000000000')
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.