seek operation in python

Chris Angelico rosuav at gmail.com
Wed Apr 29 20:33:19 EDT 2015


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])

That will print out the seventh line (counting from zero; take
lines[6] if you want to count from one), rather than seeking to byte
position 7 and printing out from there to the end of a line.

I've made a few other changes in the example, too:

1) Not that it's a big deal, but I used "f' rather than "file",
because the latter is a built-in name in Python 2, and it's safer not
to shadow.
2) A 'with' block ensures that the file is closed promptly.
3) Parentheses around your 'print' make it compatible with the
function form as well as the statement.

They're all small changes, but clean code is good code :)

ChrisA



More information about the Python-list mailing list