What Is the Perfect Counterpart in Python for "While Not Eof"

What is the perfect counterpart in Python for while not EOF

Loop over the file to read lines:

with open('somefile') as openfileobject:
for line in openfileobject:
do_something()

File objects are iterable and yield lines until EOF. Using the file object as an iterable uses a buffer to ensure performant reads.

You can do the same with the stdin (no need to use raw_input():

import sys

for line in sys.stdin:
do_something()

To complete the picture, binary reads can be done with:

from functools import partial

with open('somefile', 'rb') as openfileobject:
for chunk in iter(partial(openfileobject.read, 1024), b''):
do_something()

where chunk will contain up to 1024 bytes at a time from the file, and iteration stops when openfileobject.read(1024) starts returning empty byte strings.

How to read user input until EOF?

Use file.read:

input_str = sys.stdin.read()

According to the documentation:

file.read([size])

Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached.

>>> import sys
>>> isinstance(sys.stdin, file)
True

BTW, dont' use input as a variable name. It shadows builtin function input.

Inspecting and closing a python generator

I think you may want to use an iterator class instead -- it's implemented with a standard Python class and can have whatever extra attributes you need (such as an exhausted flag).

Something like the following:

# untested
class file_iter():
def __init__(self, file_name):
self.file = open(file_name)
self.counted_lines = 0
self.exhausted = False
def __iter__(self):
return self
def __next__(self):
if self.exhausted:
raise StopIteration
try:
next_line = self.file.readline()
self.counted_lines += 1
return next_line
except EOFError:
self.file.close()
self.exhausted = True
raise StopIteration

Can't figure out EOF error in python

I didn't hit your specific error, but it would have been hard to tell if I had based on your description. In the future, you should post your stack trace with line exceptions.

What I did find was that you had an infinite loop in your code. This part:

while True:
next2 = raw_input("> ")
if next2 == "take honey":
# snip

Never would have exited. True will always be True, so it just keeps prompting you with the raw_input. By changing the rest of that function to look like this...

while True:
next2 = raw_input("> ")
if next2 == "take honey":
dead("The bear looks at you then pimp slaps your face off.")
elif next2 == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next2 == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your crotch off.")
elif next2 == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."

...we are telling Python to take the results of the prompt stored in next2 and evaluate the rest of the checks. This way, it will exit the function by calling other functions such as dead(), or gold_room(). This will exit the bear_room() function even though the while True condition has never exited. While loops are exited when the condition evaluates to False. Because True will never equal False, we have to exit some other way, such as calling another function like dead() which will terminate by calling exit().



Related Topics



Leave a reply



Submit