PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » File Handling » Python File Seek(): Move File Pointer Position

Python File Seek(): Move File Pointer Position

Updated on: July 2, 2021 | Leave a Comment

Python offers several methods for file handling. In addition to the standard operations like reading and writing to the files, there are methods to manipulate the file pointer effectively.

In this tutorial, you’ll learn how to use the seek() function to move the position of a file pointer while reading or writing a file.

Table of contents

  • What is seek() in Python
  • How to Use seek() Method
    • Example
  • Seek the Beginning of the File
  • Seeking The End of File
  • Seek From The Current Position
  • Seek backward With Negative Offset
  • tell() Function To Get File Handle Position
  • Summary

Goals of this lesson:

  • Learn to use the seek() method to move the file cursor ahead or backward from the current position
  • Learn to move the file pointer to that start or end of the file
  • Learn to move the file pointer backward from the end of the file
  • Get the current position of the file handle

What is seek() in Python

The seek() function sets the position of a file pointer and the tell() function returns the current position of a file pointer.

A file handle or pointer denotes the position from which the file contents will be read or written. File handle is also called as file pointer or cursor.

For example, when you open a file in write mode, the file pointer is placed at the 0th position, i.e., at the start of the file. However, it changes (increments) its position as you started writing content into it.

Or, when you read a file line by line, the file pointer moves one line at a time.

Sometimes we may have to read only a specific portion of the file, in such cases use the seek() method to move the file pointer to that position.

For example, use the seek() function to do the file operations like: –

  • Read a file from the 10th character.
  • Directly jump to the 5th character from the end of the file.
  • Add new content to file after a particular position.

How to Use seek() Method

To change the file handle’s position use seek() method. As we discussed, the seek() method sets the file’s current position, and then we can read or write to the file from that position.

Syntax:

f.seek(offset, whence)

How many points the pointer will move is computed from adding offset to a reference point; the reference point is given by the whence argument.

The allowed values for the whence argument are: –

  • A whence value of 0 means from the beginning of the file.
  • A whence value of 1 uses the current file position
  • A whence value of 2 uses the end of the file as the reference point. 

The default value for the whence is the beginning of the file, which is 0

Refer to the below table for clear understanding.

Seek OperationMeaning
f.seek(0)Move file pointer to the beginning of a File
f.seek(5)Move file pointer five characters ahead from the beginning of a file.
f.seek(0, 2)Move file pointer to the end of a File
f.seek(5, 1)Move file pointer five characters ahead from the current position.
f.seek(-5, 1)Move file pointer five characters behind from the current position.
f.seek(-5, 2)Move file pointer in the reverse direction. Move it to the 5th character from the end of the file
File seek function

Example

Consider the following example where we are reading a text file contents with the offset as 6. It means we will start reading the file directly from the 6th character.

text file
text file
with open(r'E:\demos\files_demos\sample.txt', "r") as fp:
    # Moving the file handle to 6th character 
    fp.seek(6)
    # read file
    print(fp.read())

Output

line
Second line
Third line
Fourth line
Fifth line
Sixth line
Seventh line
Eighth line 

As you can see in the output, the first six characters are missing.

Seek the Beginning of the File

We can move the file pointer to the beginning of the file using the seek() method by passing the setting whence to 0.

The 0 indicates the first byte, which is the beginning of the file.

Example

Let’s see how to bring the file cursor to the beginning of the file.

In this example, we are writing to the text file. After adding content, we wanted to move the pointer to the beginning of the file to read the entire file.

# open file in write and read mode w+
with open(r'E:\demos\files_demos\test.txt', "w+") as fp:
    # add content
    fp.write('My First Line\n')
    fp.write('My Second Line')
    # move pointer to the beginning
    fp.seek(0)
    # read file
    print(fp.read())

Output

My First Line
My Second Line

Seeking The End of File

Set whence to 2 and the offset to 0 to move the file pointer to the end of the file.

  • In the below example, we will perform the following three operations
  • We will move the file pointer at the end of the file and write new content
  • Next, we will move the file pointer at the start of the file and write fresh content at the beginning of the file.
  • Again, we will move the file pointer to the end of the file and write more content.

Example:

Let’s see how to move the file cursor to the end of the file. We will use the existing file for this operation and open a file in read and write mode.

# open file for reading and writing  a+
with open(r'E:\demos\files_demos\test.txt', "r+") as fp:
    # Moving the file handle to the end of the file
    fp.seek(0, 2)

    # Inserting new content to the end of the file
    fp.write("\nThis content is added to the end of the file")

    # moving to the beginning 
    # again read the whole file
    fp.seek(0)
    print(fp.read())

Output

My First Line
My Second Line
This content is added to the end of the file

Seek From The Current Position

We can move the file pointer few positions ahead from the current position by setting the whence to 1 and offset to the number of the position you want to move.

For example, the current file pointer is at 20th position, and you wanted to jump to the 75th character then set offset to 50 and whence to 1.

We will use the existing file for this operation and open a file in read and write mode.

Note:

If your using seek() function in text files (those opened without a b in the access mode), only seeks relative to the beginning of the file are allowed.

If you try to move the file handle from the current position you’ll get an io.UnsupportedOperation: can't do nonzero cur-relative seeks error.

So open the file in binary mode if you want to move the file pointer ahead or behind from the current position

Example: Move the file handle 10 points ahead from current position.

Note:

  • Open file in binary mode. For reading use the rb, for writing use the wb, and for both reading and writing use rb+.
  • Convert byte to string if you are reading a text file.
# Open file for reading in Binary mode
with open(r'E:\demos\files_demos\test.txt', "rb") as fp:
    # Move the file handle to the 5th character
    # from the beginning of the file
    fp.seek(3)
    # read 5 bytes and convert it to string
    print(fp.read(5).decode("utf-8"))

    # Move the fp 10 points ahead from current position
    # read 5 bytes and convert it to string
    fp.seek(10, 1)
    # again read 6 bytes
    print(fp.read(6).decode("utf-8"))

Seek backward With Negative Offset

In some cases, we have to read characters from the end of the file. to do that, we need to move the file pointer in a reverse direction.

Here, you’ll learn how to seek file handle backward from current position as well as from the end of file.

For example, move to the 10th character from the end of the file. This can be done by setting the offset corresponding to the end of the file.

Example:

In this example, we are opening the file in the read binary mode (rb) and pass the offset corresponding to the end of the file.

# Open file for reading in binary mode
with open(r'E:\demos\files_demos\test.txt', "rb") as fp:
    # Move in reverse direction
    # move to the 40th character from the end of the file
    fp.seek(-40, 2)
    # read 11 bytes and convert it to string
    print(fp.read(11).decode("utf-8"))

Output

content is

Use the below code to Seek backwards from current position

# Open file for reading in binary mode
with open(r'E:\demos\files_demos\test.txt', "rb") as fp:
    # read first 8 bytes
    print(fp.read(8).decode('utf-8'))
    # Move in reverse direction
    # move to the 5th behind from current position
    fp.seek(-5, 1)
    # read 10 bytes and convert it to string
    print(fp.read(10).decode("utf-8"))

Output:

My First
First Line

tell() Function To Get File Handle Position

While the file’s access mode implies the type of operation that we intend to perform in the file, it also determines the filehandle position. For example, if the file is opened in reading, the file handle will be in the beginning, and after reading the entire file, it will be in the last character, which is the End of the File.

We can get the file handle current position using the tell() method.

Syntax:

file_object.tell()

There are no arguments for this method. The return value is the integer representing the file handle position.

# open file for reading and writing  r+
with open(r'E:\demos\files_demos\test.txt', "r+") as fp:
    # Moving the file handle to the end of the file
    fp.seek(0, 2)

    # getting the file handle position
    print('file handle at:', fp.tell())

    # writing new content
    fp.write("\nDemonstrating tell")

    # getting the file handle position
    print('file handle at:', fp.tell())

    # move to the beginning
    fp.seek(0)
    # getting the file handle position
    print('file handle at:', fp.tell())

    # read entire file
    print('***Printing File Content***')
    print(fp.read())
    print('***Done***')

    # getting the file handle position
    print('file handle at:', fp.tell())

Output

file handle at: 75
file handle at: 95
file handle at: 0

***Printing File Content***
My First Line
My Second Line
This content is added to the end of the file
Demonstrating tell
***Done***

file handle at: 95

Summary

In this module, we have seen how to use the filehandle to move to different parts of the file. We saw how to use the seek() and tell() methods to manipulate the filehandle position to add new content or read certain portions of the file.

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python File Handling

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Posted In

Python Python File Handling
TweetF  sharein  shareP  Pin

Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com