In the below program, we will learn,
在下面的程序中,我们将学习,
How to set the offset in the file to read the content from the given offset/position?
如何在文件中设置偏移量以从给定的偏移量/位置读取内容?
How to find the offset/position of the current file pointer?
如何找到当前文件指针的偏移量/位置?
Prerequisite:
先决条件:
Python程序演示在文件中设置偏移量的示例 (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
翻译自: https://www.includehelp.com/python/setting-file-offsets-in-python.aspx