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)
- offset: The number of bytes to move the file pointer can be positive or negative.
- from_where: The reference point from which the offset is applied.
- Whence: This is an optional argument specifying the reference point for the offset. It can take one of the following values:
0 (default): The file's beginning.
1: The current file position.
2: The file's end.
- 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.
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 1: 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
- seek(-7, 2) moves the file pointer 7 bytes before file end.
- read() begins from that position to the end of the file.
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.
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
- eek(5) displaces the file pointer by 6 bytes (0 indexing),
- read(10) reads the next 10 bytes from that position.
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
- seek(10) moves the file floater to the 11th byte (position 10).
- write("INSERTED") writes the string "INSERTED" starting from that position.
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
- seek(-5, 2) displaces the file pointer stepped 5 bytes before the file end (negative offset with whence=2).
- read() read from that point (5 bytes before the end of the file) to the end of the file.
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
- seek(10) moves the file floater to the 11th byte (position 10).
- read() reads the rest of that from the file.
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:
- seek(16) moves the pointer to byte 16, skipping the PNG header.
- read(4) reads the next 4 bytes, representing the image width in big-endian format.
- int.from_bytes() converts the byte data into an integer.
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)
- offset: Number of bytes by which to move the pointer.
- 0: Refers to the position at the beginning of the file.
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
- Set the pointer at byte 10 (from the start of the file).
- Read the next 5 bytes from that position.
- Print the data that contains content starting from byte 10.
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
- The readline() reads Line 1 and prints it.
- After calling seek(0, 0), the cursor is moved back to the start of the file, so the second readline() rereads Line 1 and prints it.
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)
- offset: Specifies how many bytes must be moved from the current position.
- 1: Indicates the movement concerning the current position of the file pointer.
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
- The pointer is moved 10 bytes ahead of its present file position.
- After this, the next 5 bytes are read starting from that position.
- The data that is read is printed, showing contents from the position of the new pointer.
Output
is an
3. 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)
- offset: Refers to how many bytes to move the pointer from the end of the file.
- 2: Is the reference to be considered at the end of the file.
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
- Set the pointer at 10 bytes before the end of the file.
- Fetch the file contents from there.
- Print the data that shows contents starting from the end of the file.
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.
Gain Industry-Relevant Skills and Secure a Tech Job Before College Ends!
Explore ProgramFrequently 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.