python file API

Ian Kelly ian.g.kelly at gmail.com
Mon Sep 24 18:37:12 EDT 2012


On Mon, Sep 24, 2012 at 4:14 PM, Chris Angelico <rosuav at gmail.com> wrote:
> file.pos = 42 # Okay, you're at position 42
> file.pos -= 10 # That should put you at position 32
> foo = file.pos # Presumably foo is the integer 32
> file.pos -= 100 # What should this do?

Since ints are immutable, the language specifies that it should be the
equivalent of "file.pos = file.pos - 100", so it should set the file
pointer to 68 bytes before EOF.

> foo -= 100 # But this sets foo to the integer -68
> file.pos = foo # And this would set the file pointer 68 bytes from end-of-file.

Which is the same result.

> I don't see it making sense for "file.pos -= 100" to suddenly put you
> near the end of the file; it should either cap and put you at position
> 0, or do what file.seek(-100,1) would do and throw an exception.

I agree, but the language doesn't allow those semantics.

Also, what about the use of `f.seek(0, os.SEEK_END)` to seek to EOF?
I'm not certain what the use cases are, but a quick google reveals
that this does happen in real code.  If a pos of 0 means BOF, and a
pos of -1 means 1 byte before EOF, then how do you seek to EOF without
knowing the file length?



More information about the Python-list mailing list