fp = open("a.txt") #do many things with fp c = fp.read() if c is None: print 'fp is at the eof'
Besides the above method, any other way to find out whether is fp is already at the eof?
Python doesn't have built-in eof detection function but that functionality is available in two ways: f. read(1) will return b'' if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.
What is this value? EOF A common misconception of students is that files have a special EOF character at the end. There is no special character stored at the end of a file. EOF is an integer error code returned by a function.
BaseException -> Exception -> EOFError The best practice to avoid EOF in python while coding on any platform is to catch the exception, and we don't need to perform any action so, we just pass the exception using the keyword “pass” in the “except” block.
The EOF in C/Linux is control^d on your keyboard; that is, you hold down the control key and hit d. The ascii value for EOF (CTRL-D) is 0x05 as shown in this ascii table . Typically a text file will have text and a bunch of whitespaces (e.g., blanks, tabs, spaces, newline characters) and terminate with an EOF.
fp.read()
reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception.
When reading a file in chunks rather than with read()
, you know you've hit EOF when read
returns less than the number of bytes you requested. In that case, the following read
call will return the empty string (not None
). The following loop reads a file in chunks; it will call read
at most once too many.
assert n > 0 while True: chunk = fp.read(n) if chunk == '': break process(chunk)
Or, shorter:
for chunk in iter(lambda: fp.read(n), ''): process(chunk)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With