"David Allen" <mda at idatar.com> says: > In article <mailman.986227337.10718.python-list at python.org>, "Vincent A. > Primavera" <vincent_a_primavera at netzero.net> wrote: > > > Hello, > > In a piece of code similar to this I am trying to read all the lines from a > > file but no more. How can I set the "range" of this loop to stop when it > > reaches the end of the file? > > > > for i in range(???): > > a = fil1.readline() > > print a > > You're going at it from the wrong way around. If > you really want to do it based on the number of lines > in the file, do this: > > lines = fil1.readlines() > > for i in range(0, len(lines)): > print lines[i] > > but better would probably be to do this: > > for line in fil1.readlines(): > print line > > IIRC, that way you don't have to have the whole damn > file in memory. Python is smart enough to assign > lines one at a time into 'line' rather than to > create an actual array. > > David Allen > http://opop.nols.com/ > ---------------------------------------- > Great minds run in great circles. I don't believe you. >>> f = open(r'd:\qp\var\publish\index.html') >>> z = f.readlines() >>> type(z) <type 'list'> It would appear that readlines() returns a list. Therefore the entire file is read in to create that list before returning. On the other hand, I have written a generator class that does what you are saying. In order for readlines() to be smart, it would have to return a generator instead of a list. - Ken Seehof kseehof at neuralintegrator.com www.neuralintegrator.com
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4