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.

Community
  • 1
  • 1
andy mcevoy
  • 378
  • 3
  • 12

1 Answers1

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')
abarnert
  • 354,177
  • 51
  • 601
  • 671