PDA

View Full Version : EOF in Python



7raTEYdCql
March 10th, 2009, 02:28 PM
Suppose if i want to break out of a loop when the input given is the EOF then what will the conditional statement be.
i=input("")

if i=="EOF":
break

Will this work

ghostdog74
March 10th, 2009, 03:06 PM
2 ways to iterate files
1) for loop


for line in open("file"):
print line

2) while loop


f=open("file")
while 1:
line=f.readline()
if not line: break
print line
f.close()

LegendofTom
March 10th, 2009, 03:08 PM
If you iterate by line, the end of the file should be the end of the loop.

WW
March 10th, 2009, 03:08 PM
One method is to catch the EOFError exception that will be raised:


>>> while True:
... try:
... s = raw_input("What is your name? ")
... except EOFError:
... print
... print "Bye."
... break
... print "Hello, %s" % s
...
What is your name? WW
Hello, WW
What is your name?
Bye.
>>>

I hit control-D at the second prompt.

7raTEYdCql
March 10th, 2009, 03:25 PM
inputfile.readline() automatically detects the end of file, when inputfile is opened in read ony mode???

7raTEYdCql
March 10th, 2009, 03:28 PM
My question is not about reading files.

I want to get input from terminal screen only, and i want to exit the loop of the program when ctrl+d(EOF) is typed. How is that done.

7raTEYdCql
March 10th, 2009, 03:30 PM
Stupid question. I think the program automatically terminates when i press ctr+d.

Thanks anyway.

7raTEYdCql
March 10th, 2009, 03:34 PM
No but i get a error when i press ctrl+d

How do i avoid this error??

WW
March 10th, 2009, 05:20 PM
Reread my post above. :)

It works with input() as well as raw_input().

slavik
March 11th, 2009, 03:47 AM
One method is to catch the EOFError exception that will be raised:


>>> while True:
... try:
... s = raw_input("What is your name? ")
... except EOFError:
... print
... print "Bye."
... break
... print "Hello, %s" % s
...
What is your name? WW
Hello, WW
What is your name?
Bye.
>>>

I hit control-D at the second prompt.
will this setup a try/catch block on ever loop iteration?

WW
March 11th, 2009, 03:53 AM
will this setup a try/catch block on ever loop iteration?
Sorry, I don't understand your question. The code catches the EOFError exception that is raised when ctrl-D is entered. The code in the 'except' block includes a 'break' statement, which exits the while loop.

danielgenin
April 26th, 2012, 04:03 PM
Sorry, I don't understand your question. The code catches the EOFError exception that is raised when ctrl-D is entered. The code in the 'except' block includes a 'break' statement, which exits the while loop.

Would it make more sense to enclose the whole while loop in try ... except, rather than having the except clause in the body of the while loop?