Skip to content
Advertisement

Reading binary lines not matching file lines after first line

I’m trying to read and print the binary data of a file but notice after reading the first line, with 128 bits, the subsequent lines printed out do not match the lines when I look at the binary data manually with notepad++.

nfp = open(new_file, 'rb')
dc = 0
ac = 0
short_lines = 0
line_string = str("")
for x in nfp.read():
    if dc == 16:
        ac += 1
        if ac == 5:
            break
        else:
            print(line_string)
        line_string = str("")
        dc = 0
        continue
        #open cmpf here and write
    else:
        dc += 1
        y = str("{:08b}".format(x))
        line_string = line_string + str(" ") + y


print(short_lines)
print("Final line count:", str(ac/128))
valk = input("Click any button to end program...")```

Expected output:

[enter image description here][1]


Actual output:

[printed data][2]

As you can see, the first line matches, but after that they are completely different. Why?


  [1]: https://i.stack.imgur.com/pKOAA.png
  [2]: https://i.stack.imgur.com/DBgJG.png

Advertisement

Answer

The problem is that when dc==16 then your program prints whole line but the current x value is skipped (it is not used anywhere). To fix this problem you may remove else like this:

for x in nfp.read():
    if dc == 16:
        ac += 1
        if ac == 5:
            break
        else:
            print(line_string)
        line_string = str("")
        dc = 0

    dc += 1
    y = str("{:08b}".format(x))
    line_string = line_string + str(" ") + y
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement