Basic file operation questions

Steve Holden steve at holdenweb.com
Thu Feb 3 07:56:25 EST 2005


Michael.Lang at jackal-net.at wrote:

> In article <mailman.1808.1107431422.22381.python-list at python.org>, 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()
> 
> 
> sure you can 
> 
> f = open("data.txt", "rb")
> while [ 1 ]:
> 	line = f.readlines()
> 	if not line:	break
> 	line = somethingelse ...
> f.close()
> 
Shall we charitably assume this was untested code? For a non-empty file 
it executes the loop body twice, once to read the whole content of the 
file and throw it away, the second time to do something else 
unspecified. The intention wasn't, therefore, entirely clear, but 
newbies should not be using it as any kind of model.

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005                      http://www.pycon.org/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list