Eof In A Binary File Using Python
Solution 1:
Once your reach the EOF, the for x in file:
loop will terminate.
withopen('myfile.chn', 'rb') as f:
i = 0for x in f:
i += 1print(x)
print('reached the EOF')
I've renamed the file
variable so that it doesn't shadow the built-in.
Solution 2:
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
Post a Comment for "Eof In A Binary File Using Python"