Testing for EOF ?

P

Pete Moscatt

I am reasonably new to python and am trying to read several lines of text
from an open file.

Typically in other languages I used to use code like:

while not EOF()
read_text_in
...


How is this achieved with python ?

Regards
Pete
 
S

Simon Brunning

I am reasonably new to python and am trying to read several lines of text
from an open file.

my_file = open('whatever.txt', 'r')
for line in my_file:
print line # Or whatever
 
S

Simon Brunning

Thanks Simon,

So the code should look like:

f=open(myfile,"r")

for some_var in f:
text=f.readline()
print text

Do I have this correct ?

Nearly - you don't need the text=f.readline() bit. A file object (as
returned to you by open()) is an iterator, and iterating over it gives
you the lines directly.

Why not give it a go? The nice thing about Python is how easy it is to
try stuff like this out at the interactive prompt. Err, *one* of the
nice things, that is. ;-)

BTW, newbies are more than welcome here, but there is a python-tutor
list[1] which might be more your speed if you are quite new to Python.
There are also a number of tutorials available[2] . I'd recommend
either the standard tutorial[3] or Dive Into Python[4] for someone
like you who already knows how to program but doesn't know Python.

Welcome to Python, and have fun.

--
Cheers,
Simon B,
(e-mail address removed),
http://www.brunningonline.net/simon/blog/
[1] http://mail.python.org/mailman/listinfo/tutor
[2] http://www.python.org/moin/BeginnersGuide/Programmers
[3] http://www.python.org/doc/current/tut/
[4] http://diveintopython.org/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,232
Messages
2,571,168
Members
47,803
Latest member
ShaunaSode

Latest Threads

Top