Setting file offsets in Python

17 Sep, 2021
Prerequisite: seek(), tell()
Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer within the file. offset is used later on to perform operations within the text file depending on the permissions given, like read, write, etc. 
Before starting let recall some basic methods for file handling:
seek(): In Python, seek() function is used to change the position of the File Handle to a given specific position. The file handle is like a cursor, which defines where the data has to be read or written in the file.
Syntax: f.seek(offset, from_what), where f is file pointer
Parameters:Offset: Number of positions to move forwardfrom_what: It defines point of reference.
tell(): Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Sometimes it becomes important for us to know the position of the File Handle. tell() method can be used to get the position of File Handle. tell() method returns the current position of the file object. This method takes no parameters and returns an integer value. Initially file pointer points to the beginning of the file(if not opened in append mode). So, the initial value of tell() is zero.
Syntax : f.tell() 
Return: This method returns the current position of the file read/write pointer within the file.
Step 1: Creating a text file.
Let’s create a text file “emails.txt” containing multiple emails to demonstrate the working of offset :
Python3
# WRITING OPERATIONS# creates a file named emails.txtfhand = open("emails.txt", "w") # this enters the values into the filefhand.write('''stephen.marquard@uct.ac.zastephen.marquard@uct.ac.zalouis@media.berkeley.edulouis@media.berkeley.edulouis@media.berkeley.edulouis@media.berkeley.eduray@media.berkeley.eduray@media.berkeley.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.educwen@iupui.edu''') # closing the filefhand.close()
This creates a file “emails.txt” and fills it with emails.
Step 2: Let’s check the content of the emails.txt file that we just created by writing this code :
Python3
# opening the file with reading permissionsfhand = open("emails.txt", "r") # print the content of the whole fileprint(fhand.read()) # close the filefhand.close()
Output:
Step 3:
After creating the “emails.txt” file. We read it by opening it once again, this time with reading permissions, This sets an offset named “fhand” to the beginning of the file,i.e., in position 0. We can check that by using this code :
Python3
# open the filefhand = open("emails.txt", "r") # check default value of offsetprint(f"The default position of offset is: {fhand.tell()}")
Output:
The default position of offset is: 0
Step 4: We write a program that asks the user to enter the number of characters they want to see from the beginning of the file.
Python3
# reading first nth charactersn = 40characters = fhand.read(n)print(f"First {n} Characters : ", characters)
Output:
First 40 Characters :  stephen.marquard@uct.ac.za
stephen.marqu
Here I entered to display 40 characters.
Step 5: We then check the position of the offset by using the tell() function. We use this code:
Python3
# Checking the current offset/positionoffset = fhand.tell()print("Current position of the offset:", offset)
Output:
Current position of the offset: 41
By covering 40 characters, the offset now acquires the 41st position. 
Step 6: Now, if we want to change the current position of the offset to any position we want, we can do that using the seek() function. By, passing the position we want the offset to be at, as an argument for the seek function, we can make the offset, jump to that position. We can confirm using this code:
Python3
# Repositioning the offset to the beginningoffset = fhand.seek(0)print("Offset after using seek function : ", offset) # closing the filefhand.close()
Output:
Offset after using seek function :  0
As we can see in the code above, the offset jumps to the beginning of the file as we gave the argument of “0” in the set function. And the offset value as displayed in the output will be :
sweetyty
sagar0719kumar
Picked
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function