Smith Smith - 3 months ago 19
Python Question

EOF in a binary file using python

I've made a code to read a binary file as follows :

file=open('myfile.chn','rb')
i=0
for x in file:
i=i+1
print(x)
file.close()


and the result as follows (a part of it) :
b'\x00\x00\x80?\x00\x00\x00\x005.xx\x00S\xd4\n'


How can i detect the EOF of this binary file? Let say i want to print() after i find the EOF. I tried this, but nothing happened.

if (x=='\n'):
print()


(updated)

@aix: let say that the file have few lines of results,just like the example, each line has '\n' at the end and i want put a space between each line.

b'\x00\x00\x80?\x00\x00\x00\x005.xx\x00S\xd4\n'

b'\x82\x93p\x05\xf6\x8c4S\x00\x00\xaf\x07j\n'


How can i do this?

NPE NPE
Answer

Once your reach the EOF, the for x in file: loop will terminate.

with open('myfile.chn', 'rb') as f:
   i = 0
   for x in f:
      i += 1
      print(x)  
print('reached the EOF')

I've renamed the file variable so that it doesn't shadow the built-in.

Comments