How to find out whether a file is at its `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)
Find out if file pointer is at EOF in Python
Based on martijns comment you can use the tell
but I really don't see how it is going to make a difference:
import os
R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)
while R.f.tell() < n:
line = R.f.readline()
print(line)
print("Not at EOF")
print("At EOF")
Where R.f
is the file object from your class in the previous question but you cannot use tell in the same way using islice.
Or using it using if's to be more like the logic in your question:
import os
R.f.seek(0, os.SEEK_END)
n = R.f.tell()
R.f.seek(0)
while True:
if R.f.tell() != n:
line = R.f.readline()
print(line)
print("Not at EOF")
else:
print("At EOF")
break
How to detect EOF when reading a file with readline() in Python?
From the documentation:
f.readline()
reads a single line from the file; a newline character (\n
) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; iff.readline()
returns an empty string, the end of the file has been reached, while a blank line is represented by'\n'
, a string containing only a single newline.
with open(file_name, 'r') as i_file:
while True:
line = i_file.readline()
if not line:
break
# do something with line
Detecting EOF in C
EOF
is just a macro with a value (usually -1). You have to test something against EOF
, such as the result of a getchar()
call.
One way to test for the end of a stream is with the feof
function.
if (feof(stdin))
Note, that the 'end of stream' state will only be set after a failed read.
In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.
How to check for EOF in Python?
You might find it easier to solve this using itertools.groupby.
def get_text_blocks(filename):
import itertools
with open(filename,'r') as f:
groups = itertools.groupby(f, lambda line:line.startswith('-- -'))
return [''.join(lines) for is_separator, lines in groups if not is_separator]
Another alternative is to use a regular expression to match the separators:
def get_text_blocks(filename):
import re
seperator = re.compile('^-- -.*', re.M)
with open(filename,'r') as f:
return re.split(seperator, f.read())
How to find out if offset cursor is at EOF with lseek()?
lseek
returns the (new) position. If it's acceptable that the file position is at the end after the test, the following works:
off_t old_position = lseek(fd, 0, SEEK_CUR);
off_t end_position = lseek(fd, 0, SEEK_END);
if(old_position == end_position) {
/* cursor already has been at the end */
}
Now, the cursor is at the end, whether it already has been there or not; to set it back, you can do lseek(fd, old_position, SEEK_SET)
afterwards.
(I omitted checks for errors (return value of (off_t)-1
) for sake of shortness, remember to include them in the real code.)
An alternative, though using another function, would be to query the current position as above and fstat
the file to see if the st_size
field equals the current position.
As a note, the end-of-file condition is set for streams (FILE *
, not the int
file descriptors) after an attempt to read past the end of the file, the cursor being at the end is not enough (that is, this approach is not the file descriptor equivalent to feof(stream)
).
How to detect EOF when input is not from a file?
Just iterate over sys.stdin
; then there is no need to explicitly check for the end of the input; the iterator will raise StopIteration
when it reaches the ed of the input.
import sys
for query in sys.stdin:
query = query.strip()
if query in phone_book:
print("{}={}".format(query, phone_book[query]))
else:
print("Not found")
Related Topics
Return and Yield in the Same Function
Python Overwriting Variables in Nested Functions
Checking File Permissions in Linux with Python
Parsing .Properties File in Python
Generate a List of Datetimes Between an Interval
What Is the Point of Setlevel in a Python Logging Handler
How to Convert Column with List of Values into Rows in Pandas Dataframe
Failedpreconditionerror: Attempting to Use Uninitialized in Tensorflow
Upload Image Using Post Form Data in Python-Requests
Is Close() Necessary When Using Iterator on a Python File Object
Subsampling Every Nth Entry in a Numpy Array
Wordnet Lemmatization and Pos Tagging in Python
How to Set the Default Color Cycle for All Subplots with Matplotlib
How to Remove the First Item from a List
Why Is Adding Attributes to an Already Instantiated Object Allowed
Why Doesn't List Have Safe "Get" Method Like Dictionary
Does Tkinter Have a Table Widget
Rreplace - How to Replace the Last Occurrence of an Expression in a String