Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out whether a file is at its `eof`?

Tags:

python

file

eof

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?

like image 375
Alcott Avatar asked Apr 13 '12 11:04

Alcott


People also ask

How do I know if EOF is reached in Python?

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.

Do files end with EOF?

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.

How do you specify EOF in Python?

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.

What character is EOF?

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.


1 Answers

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) 
like image 132
Fred Foo Avatar answered Oct 13 '22 05:10

Fred Foo