python定位文件位置_在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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值