[Tutor] Extracting lines in a file

Christian Witts cwitts at compuscan.co.za
Tue Apr 6 10:13:04 CEST 2010


Alan Gauld wrote:
>
> "ranjan das" <ranjand2005 at gmail.com> wrote
>
>> For instance lets say the unique string is "documentation" (and
>> "documentation" occurs more than once in the file). Now, on each 
>> instance
>> that the string "documentation" occurs in the file,  I want to read 
>> the 25th
>> line (from the line in which the string "documentation" occurs)
>>
>> Is there a goto kind of function in python?
>
> There is a seek() function but it would require the lines to be of
> constant length. Its probably easier to just use a loop:
>
> def file_jump(fileobj, n =1):
>      for line in range(n):
>            fileobj.readline()
>
> That will move the file pointer forward n lines.
>
> Note, if the jumps can overlap the original then you might want
> to  use tell() before the jump to store the original location then
> use seek() to go back. (eg if the trigger was in line 5 and the
> jump was 7 lines but  the trigger also occured in line 10)
>
> Pseudocode:
>
> for line in file:
>     if trigger in line:
>         marker = file.tell()
>         file_jump(file, jumps[trigger])
>         process_file_data()
>         file.seek(marker)   # go back to original position
>
> HTH,
>
>

If you know the line numbers you can use the linecache module to get any 
line from any file for eg.

 >>> import linecache
 >>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\n'

If what you require is more complex than simply that then you might be 
better off doing line-for-line processing on the file.

-- 
Kind Regards,
Christian Witts




More information about the Tutor mailing list