Home » Python

Python | Read file from given index (Example of tell() and seek())

In this tutorial, we are going to learn about two important methods of python file handling – tell() and seek(), here we will learn how to set file pointer position at a specific position and how to read content from there?
Submitted by Pankaj Singh, on December 30, 2018

1) tell() in python file handling

This method returns the current position of file pointer.

2) seek() in python file handling

It set the position of file pointer at a specific position.

Syntax:

    file_object.seek(offset, whence)

Here,

  1. offset is the position of read/write pointer of the file.
  2. whence is an optional argument, it has 3 values
    • 0 – to seek the file pointer from current position
    • 1 – to seek the file pointer from starting position of the file
    • 2 – to seek the file pointer from ending position of the file

Example:

def main():
    fo = open("data.txt","wt")
    fo.write("Hello world, how are you? Here, you are learning python")
    fo.close()
    fo = open("data.txt","r")
    print("Name of the File : ",fo.name)
    str=fo.read(10)
    print("Read String is till 10       : ",str)
    pos= fo.tell()
    print("Current Position             : ",pos)
    str=fo.read(10)
    print("Read String is till next 10  : ",str)
    pos= fo.tell()
    print("Current Position             : ",pos)
    print()
    print("Sending Pointer back to Top")
    pos = fo.seek(0,0)
    print("Current Position             : ",pos)
    str=fo.read(25)
    print("Read String is till 25       : ",str)
    pos= fo.tell()
    print("Current Position             : ",pos)
    fo.close()
if __name__=="__main__":main()

Output

Name of the File :  data.txt
Read String is till 10       :  Hello worl
Current Position             :  10
Read String is till next 10  :  d, how are
Current Position             :  20

Sending Pointer back to Top
Current Position             :  0
Read String is till 25       :  Hello world, how are you?
Current Position             :  25





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.