Python seek()函数
文件处理的概念用于保存程序运行后产生的数据或信息。与 C、C++、 Java等其他编程语言一样, Python也支持文件处理。
Refer the below article to understand the basics of File Handling.
- File Handling in Python.
- Reading and Writing to files in Python
寻求()方法
在Python中,seek()函数用于将文件句柄的位置更改为给定的特定位置。文件句柄就像一个游标,它定义了必须从哪里读取或写入文件中的数据。
Syntax: f.seek(offset, from_what), where f is file pointer
Parameters:
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.
参考点由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."
Python3
# 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 position
print(f.tell())
print(f.readline())
f.close()
Python3
# 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()
输出:
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.'
Python3
# 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.