Q:

Setting file offsets in Python

belongs to collection: Python file handling programs

0

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?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Read a program from another file in Python... >>
<< Python program to count total number of uppercase ...