[Edu-sig] Teaching about files

John Zelle john.zelle at wartburg.edu
Mon Nov 8 01:09:13 CET 2004


Kent,

I'm with you. In my book, I mention read, readline and readlines, but 
virtually all the programs just make use of the "for line in file" 
idiom. Of course in another chapter I use readline and a while loop, but 
that's just to show how to do an end-of-file loop for those unfortunate 
souls who will have to process files in a different language.

The read(n) code is more useful for situations like reading from network 
sockets.

Just my two cents.

--John


Kent Johnson wrote:

> I'm getting ready to teach about files this week.
>
> I'm not too happy with this chapter in Dawson. He spends quite a lot 
> of time on f.read(n) and f.readline(n) and very little on 'for line in 
> f:'.
>
> In several months of answering questions on the Tutor list, I have 
> seen many programs whose structure is (or could be) like this:
> f = open(...)
> for line in f:
>   data = line.split() # or some variation of this
>   # do something with data
>
> Sometimes the programs are written with readlines(), sometimes it is 
> f.read() followed by split('\n'), but it's all the same idea and the 
> best way to express it is with 'for line in f:'.
>
> On the other hand, I can't remember any use of f.read(n) on the Tutor 
> list at all. And it's hard to imagine why I would use f.readline(n); 
> why not just f.readline() and process the line data? (Maybe if lines 
> could be gargantuan...)
>
> So my question is, am I missing something here? Is f.read(n) 
> important? I want to de-emphasize f.read(n) and ignore f.readline(n), 
> and emphasize 'for line in f:', with f.read(), f.readline() and 
> f.readlines() also covered.
>
> Thanks,
> Kent
> _______________________________________________
> Edu-sig mailing list
> Edu-sig at python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
>


More information about the Edu-sig mailing list