Basic file operation questions

Peter Otten __peter__ at web.de
Thu Feb 3 07:25:06 EST 2005


Peter Nuttall wrote:

> On Wed, Feb 02, 2005 at 11:47:41PM -0500, Caleb Hattingh wrote:
>> Hi Alex
>> 
>> Assuming you have a file called "data.txt":
>> 
>> ***
>> f = open('data.txt','r')
>> lines = f.readlines()
>> f.close()
>> for line in lines:
>>     print line
>> ***
>>
> 
> Can you not write this:
> 
> f=open("data.txt", "r")
> for line in f.readlines():
> #do stuff to line
> f.close()
> 
> Pete

Yes, you can even write

f = open("data.txt")
for line in f:
    # do stuff with line
f.close()

This has the additional benefit of not slurping in the entire file at once.
Be aware, though, that this (newer) style of using a file as an iterator
doesn't mix well with seek() operations.

Peter



More information about the Python-list mailing list