file.seek()

语法:fileObject.seek(offset,whence)

  • offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
  • whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
    '1,2'模式需要'b'二进制模式打开文件,否则报错。

foo.txt

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line


下面过程是连贯的,我插入|引用做结果显示

fo=open('foo.txt','r+')
#使用seek(),tell(),truncate()等功能须用'读写'模式。
print('filename:',fo.name)
line1=fo.readline()
print('line1:',line1)
pos=fo.tell()
print('the pos is>%s'%pos)

$ py seek.py foo.txt
filename: foo.txt
line1: This is 1st line
the pos is>18


fo.seek(0) #指针定位文件首位
line1_1=fo.readline()
print('line1_1:',line1_1)
pos=fo.tell()
print('the pos is>%s'%pos)

line1_1: This is 1st line
the pos is>18


print('filename:',fo.name)
fo.seek(3,0)#指针定位文件首位,向后偏移3个字符
line1_2=fo.readline()
print('line1_2:',line1_2)
pos=fo.tell()
print('the pos is>%s'%pos)

line1_2: s is 1st line
the pos is>18


#使用seek(x,1/2)模式定位,须使用带有'b'二进制模式.
#fo=open('foo.txt','rb+')
fo.seek(5,1) #从当前位置(接上,即'∧This is 2nd line')向后偏移5个字符
line2=fo.readline()
print('line2:',line2)
pos=fo.tell()
print('the pos is>%s'%pos)

line2: b'is 2nd line '
the pos is>36


#fo=open('foo.txt','rb+')
fo.seek(-4,2) #'2'定位尾部,偏移量为负值,向前偏移4个字符.
line3=fo.readline()
print('line3:',line3)
pos=fo.tell()
print('the pos is>%s'%pos)

line3: b'line'
the pos is>88

原文地址:https://www.cnblogs.com/deepblue775737449/p/8280646.html