在Python中设置文件偏移
在以下程序中,我们将学习,
如何设置文件中的偏移量以从给定的偏移量/位置读取内容?
如何找到当前文件指针的偏移量/位置?
先决条件:
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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短