在Python中定位文件位置
tell()方法告诉您文件中的当前位置;换句话说,下一次读取或写入将发生在从文件开头开始的那么多个字节处。
seek(offset[,from])方法更改当前文件位置。offset参数指示要移动的字节数。from参数指定要从中移动字节的参考位置。
如果from设置为0,则意味着将文件的开头用作参考位置,1意味着将当前位置作为参考位置,如果将其设置为2,则将文件的末尾用作参考位置。。
示例
让我们获取一个我们在上面创建的文件foo.txt。
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
# Check current position
position = fo.tell()
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()这产生以下结果-
Read String is : Python is Current file position : 10 Again read String is : Python is
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短