在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 送给学长毕业祝福语简短