Python seek() 方法

2024 年 8 月 29 日 | 阅读 3 分钟

Python 的 seek() 方法用于更改文件句柄的当前位置。文件句柄就像一个光标,用于定义要在文件中读取或写入的数据的位置。

语法

参数

Offset: 用于定义向前移动的位数。

from_where: 用于定义参考点。

注意:Python 中的 seek() 方法不返回任何值。

from_where 参数用于选择参考点。它可以接受三个值

  • 0: 0 值用于将 whence 参数设置到文件开头。
  • 1: 1 值用于将 whence 参数设置到文件的当前位置。
  • 2: 2 值用于将 whence 参数设置到文件末尾。

from_where 参数默认为 0。因此,在文本模式下,除非偏移量等于 0,否则无法将参考点设置为当前位置或结束位置。

示例 1:(用户需要读取包含以下文本的文本文件

"This is the sentence I am Writing to show the example of the seek() method working in Python."

输出

30
ing to show the example of the seek() method working in Python.

示例文本文件 -

示例 2:(方法 2)

输出

Name of the file:  text.txt
Read Line: This is the sentence I am Writing to show the example of the seek() method working in Python.

Read Line: The line no. 2 for showing the second method of writing the seek() method is python

seek() 方法也可以处理负偏移量,但仅当文件以二进制模式打开时。

示例 3:(负偏移量)

输出

25
 Writing to show the example of the seek() method working in Python.