Python with open seek

Python File Seek(): Move File Pointer Position

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

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 0 th position, i.e., at the start of the file. However, it changes (increments) its position as you started writing content into it.

Читайте также:  Setting php in environment variable

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 10 th character.
  • Directly jump to the 5 th 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.

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.

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()) 
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.

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()) 
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.

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())
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.

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.

  • 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 10 th character from the end of the file. This can be done by setting the offset corresponding to the end of the file.

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")) 

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")) 

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.

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()) 
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.

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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

Источник

Оцените статью