在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
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短