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?
By IncludeHelp Last updated : July 05, 2023

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

Python file handling programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.