码迷,mamicode.com
首页 > 其他好文 > 详细

file.seek()

时间:2018-01-13 23:43:24      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:使用   模式   source   过程   一个   二进制   setw   就是   定义   

语法: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

file.seek()

标签:使用   模式   source   过程   一个   二进制   setw   就是   定义   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!