seek operation in python

Cecil Westerhof Cecil at decebal.nl
Thu Apr 30 02:27:29 EDT 2015


Op Thursday 30 Apr 2015 02:33 CEST schreef Chris Angelico:

> On Thu, Apr 30, 2015 at 4:08 AM, siva sankari R <buddingrose11 at gmail.com> wrote:
>> file=open("input","r")
>> line=file.seek(7)
>> print line
>>
>> The above code is supposed to print a line but it prints "none". I
>> don't know where the mistake is. Help.!
>
> Going right back to the beginning... Are you aware that 'seek' works
> with byte positions? On a text file, you can't even do this, and
> even on a byte file, it won't give you the seventh line.
>
> If, as you say, it's only some eighty lines of code, the best
> solution is probably the simplest: read the whole file into memory.
>
> with open("input.cpp") as f:
> lines = f.readlines()
> print(lines[7])

Is the following not better:
    print(open('input.cpp', 'r').readlines()[7])

Time is the same (about 25 seconds for 100.000 calls), but I find this
more clear.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list