Home » Python » Python programs

Setting file offsets in Python

Python seek() and tell() methods example: Here, we are going to learn how to set offsets in Python file handing?
Submitted by IncludeHelp, on February 14, 2020

In the below program, we will learn,

  1. How to set the offset in the file to read the content from the given offset/position?
  2. How to find the offset/position of the current file pointer?

Prerequisite:

Python program to demonstrate example of setting offsets in a file

# creating a file 
f = open('file1.txt', 'w')

# writing content to the file
# first line
f.write('This is line1.\n')
# second line
f.write('This is line2.\n')
#third line
f.write('This is line3.\n')

# closing the file
f.close()

# now, reading operations ....
# openingthe file
f = open('file1.txt', 'r')
# reading 10 characters
str = f.read(10);
print('str: ', str)

# Check current offset/position
offset = f.tell();
print('Current file offset: ', offset)

# Reposition pointer at the beginning once again
offset = f.seek(0, 0);
# reading again 10 characters
str = f.read(10);
print('Again the str: ', str)

# closing the file
f.close()

Output

str:  This is li
Current file offset:  10
Again the str:  This is li






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.








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.