python seek使用_Python seek()用法及代码示例

本文介绍了Python中文件处理的seek()方法,用于改变文件句柄的位置。它接受偏移量和参考点作为参数,参考点可以是文件开头、当前位置或文件末尾。示例演示了在正向和负向偏移量下的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件处理的概念用于保留程序运行后生成的数据或信息。与其他编程语言(如C,C++,Java,Python)一样,它也支持文件处理。

Refer the below article to understand the basics of File Handling.

seek()方法

在Python中,seek()函数用于将文件句柄的位置更改为给定的特定位置。文件句柄就像一个游标,它定义了必须从何处读取或写入文件中的数据。

用法:f.seek(offset, from_what), where f is file pointer

参数:

Offset:前进的位置数

from_what:它定义了参考点。

返回:不返回任何值

参考点由from_what参数选择。它接受三个值:

0:将参考点设置在文件的开头

1:将参考点设置在当前文件位置

2:将参考点设置在文件末尾

默认情况下,from_what参数设置为0。

注意:除非偏移量等于0,否则无法在文本模式下设置当前位置/文件末尾的参考点。

范例1:假设我们必须读取一个名为“GfG.txt”的文件,其中包含以下文本:

"Code is like humor. When you have to explain it, it’s bad."

# Python program to demonstrate

# seek() method

# Opening "GfG.txt" text file

f = open("GfG.txt", "r")

# Second parameter is by default 0

# sets Reference point to twentieth

# index position from the beginning

f.seek(20)

# prints current postion

print(f.tell())

print(f.readline())

f.close()

输出:

20

When you have to explain it, it’s bad.

范例2:具有负偏移量的Seek()函数仅在以二进制模式打开文件时才起作用。假设该二进制文件包含以下文本。

b'Code is like humor. When you have to explain it, its bad.'

# Python code to demonstrate

# use of seek() function

# Opening "GfG.txt" text file

# in binary mode

f = open("data.txt", "rb")

# sets Reference point to tenth

# position to the left from end

f.seek(-10, 2)

# prints current position

print(f.tell())

# Converting binary to string and

# printing

print(f.readline().decode('utf-8'))

f.close()

输出:

47

, its bad.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值