Skip to content

Python file seek function | Read a file from index | move poin​ter

  • by

Python file seek() function sets the current file position in a file stream. The seek function is useful when operating over an open file. Using this function you can move into a file or can say used to change the current cursor position in Python.

Python file seek function

Syntax

It’s important to note that its syntax is as follows:

fileObject.seek(offset,from_what))

Parameters

  • offset – A number of positions will move.
  • from_what – defines your point of reference. (Optional)

0: Reference point is the beginning of the file

1: Reference point is the current file position

2: Reference point is the end of the file

Note: if omitted (not filled) then, from_what defaults to 0.

Return Value

It returns the new position.

Python file seek function Example

Moving to example hope you know about the file open function in python and file mode use. If note then read this tutorial – File Handling in python.

Let’s see the example of change the current file position to 9 in the file, and return the rest of the line.

Where file name is “testFile.txt” and text is “EyeHunts Python”.

f = open("testFile.txt", "r")
f.seek(9)
print(f.readline())

Output: Python

Screenshot:

Python file seek function code

What is the use of the seek() function in Python?

Answer: A python seek() function is used for a Reading file from the given index. A function has the option to set the value of the reading portion in file and position like – from the Start, End, or middle.

How to Use seek() to move file pointer in python?

Answer: Use seek() to move file pointer in python.

Example 1

Starts reading from the specific indexed character.

f = open('testFile.txt', 'r')
f.seek(3)
print(f.read())  # starts reading from the 3rd character

Output: lo Python

Example 2

Move characters ahead from the current position.

f = open('testFile.txt', 'br')
f.seek(2)
f.seek(3, 1)
print(f.read())  # starts reading from the 3rd character

Output: b’ Python’

Example 3

Move to the index character from the end of the file.

f = open('testFile.txt', 'br')

f.seek(-3, 2) # move to the 3rd character from the end of the file
print(f.read()) 

Output: b’hon’

Note: From the documentation for Python 3.2 and up. Reading a text file (those opened without b in the mode string), only seeks relative to the beginning of the file are allowed.

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Examples python file seek line of File Reading are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *