Seek Function in Python: Examples & Modes

Published: 18 Mar 2025 | Reading Time: 4 min read

Overview

File handling in programming provides for efficient storage and retrieval of data. In Python, file handling is more simplified because of functions like seek(), which provide random access to contents in a file. This flexibility allows reading or writing data from any part of a file rather than sequential processing. The seek function in Python is used to change the position of the file pointer inside the open file so that parts of the file can be accessed randomly. It operates in conjunction with the tell() function, which returns the current position of the file pointer.

Table of Contents

What is a Seek Function in Python?

The seek function in Python is an internal one used to set the current position of the file pointer in a file. A file pointer is a marker pointing to the current position in the file to either read or write data from that position. This function is most effective when working with larger files because you can set the read or write operation on the file pointer to start reading from some specific offset in the file. Sequential file processing would occur without the seek() function, which is sometimes inefficient.

Syntax of Seek Function in Python

The syntax of the seek() function in Python is:

file.seek(offset, from_where)

Parameters:

Returns: Return Value of Seek Function in Python. Briefly meaning the seek function returns an integer, representing the new position of the file cursor after moving it.

Basic Code Example

file_pointer = open("sample.txt")
current_position = file_pointer.tell()  # Get the current position
new_position = file_pointer.seek(30)  # Seek to the 30th byte
print(current_position)  # Outputs 0
print(new_position)      # Outputs 30
new_position = file_pointer.seek(12)  # Seek to the 12th byte
print(new_position)      # Outputs 12

Explanation:

The seek function moves the file cursor to the new position and returns the new position after the operation, so you know where the pointer is after seeking.

Output:

0
30
12

Example: Seek() Function with Negative Offset Value

Using seek() with negative offsets to move from the end of the file has its uses, particularly in conjunction with files with unknown lengths.

Code:

with open("sample.txt", "r") as file:
    file.seek(-7, 2)  # Move the pointer 7 bytes before the end of the file
    content = file.read()  # Read from that position to the end
    print(content)

Explanation:

Output:

file

Exceptions of seek in Python

The seek() method in Python can raise exceptions under specific conditions. The primary exception that occurs with seek(). For example, you attempt relative positions such as os.SEEK_CUR or os.SEEK_END to the non-binary or text modes, and you will get an exception io.UnsupportedOperation.

Binary Mode

In binary mode (e.g., rb, wb, rb+), the file is read and written byte by byte. This mode is typically used with binary files which are not text files.

The binary seek() function also functions like it should, and you may be able to shift the file pointer relative to the start, position, or end of the file by having the appropriate whence parameter.

Non-Binary Mode

Non-binary mode (e.g., r, w, a) is also called character mode. Files of this mode are read character by character and can be read by human beings.

In non-binary mode, attempting to use seek() relative to the current position (SEEK_CUR) or the end of the file (SEEK_END) results in an io.UnsupportedOperation exception. This is because relative seeking is not supported in text mode.

Exception Example

import os
file_handle = open('sample.txt')  # non-binary mode
file_handle.seek(765)             # This works, no exception
file_handle.seek(7, os.SEEK_CUR)  # Throws io.UnsupportedOperation
file_handle.seek(8, os.SEEK_END)  # Throws io.UnsupportedOperation

Explanation:

The cursor will be put into a new position, and no exception will be raised if the position passed to seek exceeds the file length itself, for example, in the case of seek(765); as a result, read() will return an empty result.

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can't do nonzero cur-relative seeks

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can't do nonzero end-relative seeks

Examples of Seek Function in Python

Several examples demonstrate how the seek() function works in different scenarios.

Example 1: Use of seek() in Read Mode

The seek() allows you to change the file floater's position in read mode, from where you will continue reading.

Sample.txt:

This is a sample text

Code Example:

with open("sample.txt", "r") as file:
    file.seek(5)  # Move the pointer to the 6th byte (index 5)
    content = file.read(10)  # Read the next 10 bytes
    print(content)

Explanation:

Output:

ple text

Example 2: Use of seek() in Write Mode

In write mode, you will move the file pointer to a certain position, from which you can begin writing data.

Sample.txt:

This is a sample text

Code Example:

with open("sample.txt", "r+") as file:
    file.seek(10)  # Move the pointer to the 11th byte
    file.write("INSERTED")  # Write "INSERTED" at that position

Explanation:

Output:

//After executing the code, the content of sample.txt will become:
This is a saINSERTED text

Example 3: Moving the File Pointer Using seek()

This example illustrates the use of seek() to move the search pointer to a specified position relative to the file size.

Sample.txt:

This is just a sample text file

Code Example:

with open("sample.txt", "rb") as file:
    file.seek(-5, 2)  # Move the pointer 5 bytes before the end of the file
    content = file.read()  # Read from that position to the end
    print(content)

Explanation:

Output:

just a sample file.

Example 4: Seek Forward Through the Line and Read to the End

You can combine the use of seek() to scan through the file, and then use read() to grab the rest of the data.

Sample.txt:

This is just a sample text file

Code:

with open("sample.txt", "r") as file:
    file.seek(10)  # Move the pointer to the 11th byte
    content = file.read()  # Read from that position to the end
    print(content)

Explanation:

Output:

just a sample file

Example 5: Reading the Width of a PNG File

In this example, seek() is used to inspect the metadata of a PNG image by moving to specific byte positions.

Code:

with open("image.png", "rb") as file:
    file.seek(16)  # Skip the first 16 bytes (PNG header)
    width = int.from_bytes(file.read(4), byteorder='big')  # Read the width (4 bytes)
    print(f"Width of the image: {width} pixels")

Explanation:

Output:

Width of the image: 800 pixels

Modes of the seek() Function in Python

The modes of the seek function in Python are defined below:

1. Absolute Mode

In absolute mode, the seek() function uses the position of the file pointer as an exact byte location from the beginning of the file.

Syntax:

file.seek(offset, 0)

Parameters:

data.txt:

Hello, this is a sample text file.

Code:

# Open the file in read mode
file = open("data.txt", "r")

# Move the pointer to byte 10
file.seek(10, 0)

# Read 5 bytes from the current position
data = file.read(5)

# Print the data
print(data)

# Close the file
file.close()

Explanation:

Output:

is a

2. Return Value

The seek() method does not return anything. It simply moves the file cursor to the specified position.

Here's an example where the file pointer is set at the beginning of the file:

foo.txt:

Line 1
Line 2
Line 3
Line 4
Line 5

Code:

# Open the file in read-write mode
file = open("foo.txt", "r+")

# Read the first line
line = file.readline()
print("Read Line:", line)

# Move the cursor to the beginning of the file
file.seek(0, 0)

# Read the first line again
line = file.readline()
print("Read Line:", line)

# Close the file
file.close()

Explanation:

Output:

Read Line: Line 1
Read Line: Line 1

3. Relative Mode

In relative mode, the seek() function moves the file pointer a specific number of bytes ahead or backwards from its current position.

Syntax:

file.seek(offset, 1)

Parameters:

data.txt:

Hello, this is a sample text file.

Code:

# Open the file in read mode
file = open("data.txt", "r")

# Move the pointer 10 bytes forward from the current position
file.seek(10, 1)

# Read 5 bytes from the new position
data = file.read(5)

# Print the data
print(data)

# Close the file
file.close()

Explanation:

Output:

is an

4. From End Mode

From end mode, the seek() function puts a file pointer a certain number of bytes from the end of a file.

Syntax:

file.seek(offset, 2)

Parameters:

data.txt:

Hello, this is a sample text file.

Code:

# Open the file in read mode
file = open("data.txt", "r")

# Move the pointer 10 bytes before the end of the file
file.seek(-10, 2)

# Read 5 bytes from the new position
data = file.read(5)

# Print the data
print(data)

# Close the file
file.close()

Explanation:

Output:

text

Conclusion

In conclusion, the seek() function in Python provides the ability to move the file pointer to a specific position within the file for easy random access. It takes an offset (number of bytes) and an optional from_where (reference point). seek() is very effective when reading or writing from/to specific sections of a file without allowing the entire file to be loaded into memory. Its complement is the tell() function, which shows the current file pointer position. The use of relative seeking in non-binary mode can also cause errors. Overall, seek() allows precise file manipulation and is essential in file manipulation operations.

Frequently Asked Questions

1. Explain the difference between tell and seek.

The tell function returns the current position of the file pointer, while the seek moves the pointer to a specific position. tell checks the location of the pointer while seek repositions of the pointer.

2. Define the seek command.

The seek command allows the programmer to move the file pointer to a given position for random access. The seek command requires two arguments- an offset from the beginning of the file and an optional whence argument.

3. What is file seek 0?

The seek(0, 0) returns the file pointer to the start of the file. Hence, it is used mainly to reset the position for a read operation from the beginning.

4. What does fp.seek to do in Python?

fp.seek() sets the file pointer position for a file object fp. In other words, it moves to the specified byte in the file.

5. What is Goal Seek in Python?

Goal Seek is not a built-in function but a method, technique, or process to find an algorithm output. In this case, goal finding is leveraged via optimisation libraries in Python, such as Scipy.

Related Articles


About NxtWave

NxtWave provides comprehensive programming education and career development resources. For more information, visit www.ccbp.in or contact [email protected].

Contact Information: