python seek函数whence_file.seek(offset[, whence])

file.seek(offset[, whence])

描述 (Description)

方法seek()设置文件在偏移处的当前位置。 whence参数是可选的,默认为0,表示绝对文件定位,其他值为1表示相对于当前位置的搜索,2表示相对于文件结束的搜索。

没有回报价值。 请注意,如果打开文件以使用“a”或“a +”进行追加,则在下次写入时将撤消任何seek()操作。

如果仅使用'a'打开文件以追加模式写入,则此方法基本上是无操作,但对于在追加模式下打开且启用读取的文件(模式'a +')仍然有用。

如果使用't'以文本模式打开文件,则只有tell()返回的偏移是合法的。 使用其他偏移会导致未定义的行为。

请注意,并非所有文件对象都是可搜索的。

语法 (Syntax)

以下是seek()方法的语法 -fileObject.seek(offset[, whence])

参数 (Parameters)offset - 这是文件中读/写指针的位置。

whence - 这是可选的,默认为0表示绝对文件定位,其他值为1表示相对于当前位置的搜索,2表示相对于文件结束的搜索。

返回值 (Return Value)

此方法不返回任何值。

例子 (Example)

以下示例显示了seek()方法的用法。Python is a great language

Python is a great language

#!/usr/bin/python

# Open a file

fo = open("foo.txt", "rw+")

print "Name of the file: ", fo.name

# Assuming file has following 5 lines

# This is 1st line

# This is 2nd line

# This is 3rd line

# This is 4th line

# This is 5th line

line = fo.readline()

print "Read Line: %s" % (line)

# Again set the pointer to the beginning

fo.seek(0, 0)

line = fo.readline()

print "Read Line: %s" % (line)

# Close opend file

fo.close()

当我们运行上面的程序时,它产生以下结果 -Name of the file: foo.txt

Read Line: Python is a great language.

Read Line: Python is a great language.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值