python3seek_Python3 file.seek()方法

此方没有返回值。请注意,如果文件被打开使用的是'a'或'A+'追加,任何seek()操作将在下次写时撤消。

如果该文件只打开使用 'A' 追加模式写入,这种方法本质上是一个无操作,但是读取启用(模式'A+'),它在追加模式打开的文件非常有用。

如果文件在文本模式下使用“t”,只有 tell() 返回偏移开是合法的。其他偏移时会导致不确定的行为。

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

语法

以下是 seek()方法的语法 -

fileObject.seek(offset[, whence])

参数

offset -- 这是在文件内的读/写指针的位置。

whence -- 这是可选的,默认为0表示绝对的文件定位;值是1时这意味着寻找相对于当前位置;以及值是2时寻找相对于文件的末尾。

返回值

此方法不返回任何值。

示例

下面的示例显示seek()方法的使用。

Assuming that 'foo.txt' file contains following text:

This is 1st line

This is 2nd line

This is 3rd line

This is 4th line

This is 5th line

#!/usr/bin/python3

# Open a file

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

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

line = fo.readlines()

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 opened file

fo.close()

当我们运行上面的程序,会产生以下结果 -

Name of the file: foo.txt

Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']

Read Line: This is 1st line

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值