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\r\n'
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值