文件处理的概念用于保留程序运行后生成的数据或信息。像其他编程语言(如C, C++, Java, Python)一样, 也支持文件处理.
请参阅下面的文章, 以了解文件处理的基础。 Python中的文件处理。用Python读写文件
seek()方法
在Python中, 寻求()功能用来更改文件句柄的位置到给定的特定位置。文件句柄就像一个游标, 它定义了必须从何处读取或写入文件中的数据。
语法:f.seek(offset, from_what), 其中f是文件指针
参数:
Offset:要向前移动的位置数
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.
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/70054.html