By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,702 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

Testing for EOF ?

P: n/a
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

Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Apr 4, 2005 12:21 PM, Pete Moscatt <pg*******@optushome.com.au> wrote:
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

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 18 '05 #2

P: n/a
On Apr 4, 2005 12:36 PM, Peter Moscatt <pg*******@optushome.com.au> wrote:
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,
si***@brunningonline.net,
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/
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.