Python3 File seek() Method
Overview
seek()The method is used to move the file read pointer to a specified position.
Syntax
The syntax of the seek() method is as follows:
fileObject.seek(offset[, whence])
Parameters
-
offset-- The starting offset, which represents the number of bytes to move. If negative, it means starting from a position counted backward from the end.
whence:Optional, default value is 0. It defines a parameter for the offset, indicating which position to start the offset from; 0 means from the beginning of the file, 1 means from the current position, 2 means from the end of the file.
Return Value
If the operation succeeds, the new file position is returned. If the operation fails, the function returns -1.
Examples
The following examples demonstrate the use of the seek() method:
Examples
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5) # Move to the sixth byte of the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Move to the third-to-last byte of the file
13
>>> f.read(1)
b'd'
The content of the file example.txt is as follows:
1:www.example.com 2:www.example.com 3:www.example.com 4:www.example.com 5:www.example.com
Read the file content in a loop:
Examples
The output of the above example is:
文件名为: example.txt 读取的数据为: 1:www.example.com 读取的数据为: 1:www.example.com
Other Extensions
Python3 File Methods