在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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿