python中如何使用seek来移动文件指针位置

1.文件指针的定义
python中使用seek()移动指针来位置对文件进行读写使用,文件指针来指定文件当前的位置,常常配合一些文件操作方法来使用(r+,w+,a+)
2.seek的语法解释

seek方法,移动指针
 seek第一个参数是偏移量:>0,代表向右移动,<0,代表向左移动
 seek第二个参数是:
        0:移动指针到文件开头
        1:不移动指针
        2:移动指针到末尾

python中如何使用seek来移动文件指针位置_第1张图片
python中如何使用seek来移动文件指针位置_第2张图片
python中如何使用seek来移动文件指针位置_第3张图片

f = open('/wenjian/passwd','r+')
print(f.tell())   打印指针位置
print('1',f.read(5))  read(5)表示打印第五个指针位置的字符
f.close()
打印结果
0
1 root:
f = open('/wenjian/passwd','rb')
print(f.tell())
f.seek(-1,2)   2:表示指针移动到末尾,-1:向左移动一位
print(f.tell())  查看移动之后的位置
f.seek(0)    0:移动到文件开头
print(f.tell())  查看指针位置
f.close()   关闭文件
打印结果
0
2788
0

你可能感兴趣的:(python中如何使用seek来移动文件指针位置)