在Python中设置文件偏移

在以下程序中,我们将学习,

  1. 如何设置文件中的偏移量以从给定的偏移量/位置读取内容?

  2. 如何找到当前文件指针的偏移量/位置?

先决条件:

  • Python文件 seek() 方法

  • Python文件 tell() 方法

Python程序演示在文件中设置偏移量的示例

# 创建一个文件 
f = open('file1.txt', 'w')

# 将内容写入文件
# 第一行
f.write('This is line1.\n')
# 第二行
f.write('This is line2.\n')
#第三行
f.write('This is line3.\n')

# 关闭档案f.close()# 现在,阅读操作....
# 打开文件
f = open('file1.txt', 'r')
# 阅读10个字符
str = f.read(10);
print('str: ', str)

# 检查当前偏移量/位置
offset = f.tell();
print('Current file offset: ', offset)

# 再次将指针重新定位在开头
offset = f.seek(0, 0);
# 再读10个字符
str = f.read(10);
print('Again the str: ', str)

# 关闭档案f.close()

输出结果

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