EOF in a binary file using python

2019-08-15 04:47发布

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?

2条回答
\"骚年 ilove
2楼-- · 2019-08-15 05:20

NPE's answer is correct, but I feel some additional clarification is necessary.

You tried to detect EOF using something like

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

so probably you are confused the same way I was confused until today.

EOF is NOT a character or byte. It's NOT a value that exists in the end of a file and it's not something which could exist in the middle of some (even binary) file. In C world EOF has some value, but even there it's value is different from the value of any char (and even it's type is not 'char'). But in python world EOF means "end of file reached". Python help to 'read' function says "... reads and returns all data until EOF" and that does not mean "until EOF byte is found". It means "until file is over".

Deeper explanation of what is and what is not a 'EOF' is here: http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1048865140&id=1043284351

查看更多
Summer. ? 凉城
3楼-- · 2019-08-15 05:35

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.

查看更多
登录 后发表回答