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.
Goals of this lesson:
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 0 th 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: –
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)
Code language: Python (python)
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: –
The default value for the whence is the beginning of the file, which is 0
Refer to the below table for clear understanding.
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())
Code language: Python (python)
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.
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())
Code language: Python (python)
Output
My First Line My Second Line
Set whence to 2 and the offset to 0 to move the file pointer to the end of the file.
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())
Code language: Python (python)
Output
My First Line My Second Line This content is added to the end of the file
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 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"))
Code language: Python (python)
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 10 th 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"))
Code language: Python (python)
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"))
Code language: Python (python)
Output:
My First First Line
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()
Code language: Python (python)
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())
Code language: Python (python)
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
Code language: Python (python)
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.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.