seek operation in python
rosuav at gmail.com
Thu Apr 30 02:33:19 CEST 2015
On Thu, Apr 30, 2015 at 4:08 AM, siva sankari R <buddingrose11 at gmail.com> wrote:
> 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()
That will print out the seventh line (counting from zero; take
lines 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
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 :)
More information about the Python-list