[Tutor] Line in a file
Erik Price
erikprice@mac.com
Thu, 18 Jul 2002 19:24:01 -0400
On Thursday, July 18, 2002, at 06:33 PM, Michael Montagne wrote:
> How do I go directly to an exact line number in a file?
Well, I was trying to figure this one out for ya as an exercise, but I
got stumped. So in trying answer one question, another came up. Can
anyone tell me what's wrong here?
>>> f = open('./sampletext.txt') # open a file
>>> line = f.readline() # read a line
>>> line # print it
'this is line 1\n'
>>> line2 = f.readline() # read another line relative
>>> line2 # to where we left off, print it
'this is line 2\n'
>>> f.tell() # what position are we at?
30L
>>> f.seek(0) # go back to the beginning of f
>>> f.tell() # make sure we're at the beginning
0L
>>> i # we set i to 0 earlier
0
>>> for line in f.xreadlines(): # xreadlines() sequentially reads
... i = i + 1 # lines, so this is one way to get
... if (i == 3): # a certain line from a file
... print line # (in this case line 3)
...
line 3 is high as my knee
>>> f.tell() # where are we now?
86L
>>> f.seek(0) # go back to the beginning of f
>>> f.tell() # double check
0L
>>> def printLine(fh, num): # let's make code reuseable
... c = 0
... for line in fh.xreadlines():
... c = c + 1
... if (line == num):
... fh.seek(0) # resets file pointer
... return line # returns the line we want
...
>>> data = '' # initialize a container variable
>>> data = printLine(f, 2) # try out our function
>>> data # nothing in the container!
>>> print data # nothing!
None
>>>
Why doesn't this work?
Erik