在 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

更新日期:30-Jan-2020

1K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.