Tarang Saluja
Tarang Saluja

Reputation: 125

Seek function Python

When I use the seek function, I am unable to set the whence parameter to 1. After some searching I found that I need to include a "byte--like object" so that I can set the whence parameter to 1. What does this entail, and do I always need a bytes-like object so that I can set the whence to 1 and have the offset starting from the current index position in a file?

Upvotes: 1

Views: 880

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9664

When you open file in text mode, the file-like object it returns is io.TextIOWrapper (derived from io._TextIOBase). Their seek() with regard to whence works as follows:

The default value for whence is SEEK_SET.

SEEK_SET or 0: seek from the start of the stream (the default); offset must either be a number returned by TextIOBase.tell(), or zero. Any other offset value produces undefined behaviour.

SEEK_CUR or 1: “seek” to the current position; offset must be zero, which is a no-operation (all other values are unsupported).

SEEK_END or 2: seek to the end of the stream; offset must be zero (all other values are unsupported).

I.e. you can use whence values of 1 and 2 only with offset of 0.

Upvotes: 2

Related Questions