Javatpoint Logo
Javatpoint Logo

Python seek() Method

Python seek() method is used for changing the current location of the file handle. The file handle is like a cursor, which is used for defining the location of the data which has to be read or written in the file.

Syntax:

Parameters:

Offset: This is used for defining the number of positions to move forward.

from_where: This is used for defining the point of reference.

NOTE: The seek() method in Python does not return any value.

The from_where argument is used for selecting the reference point. It can accept three values:

  • 0: The 0 value is used for setting the whence argument at the beginning of the file.
  • 1: The 1 value is used for setting the whence argument at the current position of the file.
  • 2: The 2 value is used for setting the whence argument at the end of the file.

The from_where argument is set to 0 by default. Therefore, the reference point cannot be set to the current position or end position, in the text mode, except when the offset is equal to 0.

Example1: (The user has to read the text file, which contains the following text:

"This is the sentence I am Writing to show the example of the seek() method working in Python."

Output:

30
ing to show the example of the seek() method working in Python.

Sample Text File -

Example 2: (method 2)

Output:

Name of the file:  text.txt
Read Line: This is the sentence I am Writing to show the example of the seek() method working in Python.

Read Line: The line no. 2 for showing the second method of writing the seek() method is python

The seek() method can also work with the negative offset, but only when the file is opened in binary mode.

Example 3: (negative offset)

Output:

25
 Writing to show the example of the seek() method working in Python.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA