Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Set 3 (Strings, Lists, Tuples, Iterations)
Next article icon

Setting file offsets in Python

Last Updated : 17 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 forward
from_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.

Let’s understand this with step-wise implementation:

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.txt
fhand = open("emails.txt", "w")
 
# this enters the values into the file
fhand.write('''[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]''')
 
# closing the file
fhand.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 permissions
fhand = open("emails.txt", "r")
 
# print the content of the whole file
print(fhand.read())
 
# close the file
fhand.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 file
fhand = open("emails.txt", "r")
 
# check default value of offset
print(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 characters
n = 40
characters = fhand.read(n)
print(f"First {n} Characters : ", characters)
                      
                       

Output:

First 40 Characters :  [email protected] 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/position
offset = 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 beginning
offset = fhand.seek(0)
print("Offset after using seek function : ", offset)
 
# closing the file
fhand.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 :



Next Article
Python | Set 3 (Strings, Lists, Tuples, Iterations)

S

samaldibyajyoti2012
Improve
Article Tags :
  • Python
  • Technical Scripter
  • python-file-handling
  • Technical Scripter 2020
Practice Tags :
  • python

Similar Reads

  • String rjust() and ljust() in python()
    1. String rjust() The string rjust() method returns a new string of given length after substituting a given character in left side of original string. Syntax: string.rjust(length, fillchar) Parameters: length: length of the modified string. If length is less than or equal to the length of the origin
    2 min read
  • Python List Slicing
    Python list slicing is fundamental concept that let us easily access specific elements in a list. In this article, we’ll learn the syntax and how to use both positive and negative indexing for slicing with examples. Example: Get the items from a list starting at position 1 and ending at position 4 (
    5 min read
  • Python String center() Method
    center() method in Python is a simple and efficient way to center-align strings within a given width. By default, it uses spaces to fill the extra space but can also be customized to use any character we want. Example: [GFGTABS] Python s1 = "hello" s2 = s1.center(20) print(s2) [/GFGTABS]Ou
    2 min read
  • Operator Functions in Python | Set 2
    Operator Functions in Python | Set 1 More functions are discussed in this article. 1. setitem(ob, pos, val) :- This function is used to assign the value at a particular position in the container. Operation - ob[pos] = val 2. delitem(ob, pos) :- This function is used to delete the value at a particul
    5 min read
  • Python | Set 3 (Strings, Lists, Tuples, Iterations)
    In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
    3 min read
  • Setting Precision in Python Using Decimal Module
    The decimal module in Python can be used to set the precise value of a number. The default value of the Decimal module is up to 28 significant figures. However, it can be changed using getcontext().prec method. The below program demonstrates the use of decimal module by computing the square root of
    1 min read
  • Python String - ljust(), rjust(), center()
    Strings are sequences of characters that we can manipulate in many ways. Sometimes we need to align a string to the left, right, or centre within a given space. In this article, we will explore the Difference between ljust(), just() and center(). Table of Content str.ljust()Syntax of ljust()Example
    2 min read
  • Python | Pandas tseries.offsets.BusinessDay.name
    Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the
    3 min read
  • Python | Pandas tseries.offsets.DateOffset.name
    Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the
    3 min read
  • Python | Pandas tseries.offsets.DateOffset.nanos
    Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences