UnsupportedOperation: can't do nonzero cur-relative seeks : Python

Viewed 7232

Below is my code, I am using :

with open(r'C:\Users\Manish\Desktop\File5.txt', 'r') as f:
     fo = f.read(20)
     print(fo)
     f.seek(20,1)
     fo = f.read(20)
     print(fo)

But instead of getting next lines from current position, it repeatedly showing me error. Where is the problem in my code ?

2 Answers

It seems like offset from current stream and end of stream only supported in binary mode. Which you have to open the file with

open(r'C:\Users\Manish\Desktop\File5.txt', 'rb')

Syntax:

f.seek(offset, from_what), where f is file pointer

Parameters:

Offset: Number of positions to move forward from_what: It defines point of reference.

Returns:

Does not return any value

The reference point is selected by the from_what argument. It accepts three values:

0: sets the reference point at the beginning of the file

1: sets the reference point at the current file position

2: sets the reference point at the end of the file

By default from_what argument is set to 0. Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.

Related