Python3 File seek() Method
Overview
The seek() method is used to move the file read pointer to a specified position.
Syntax
The syntax for the seek() method is as follows:
fileObject.seek(offset[, whence])
Parameters
offset -- The starting offset, which represents the number of bytes to move the offset by. If negative, it indicates starting from the倒数第几位.
whence: Optional, default value is 0. Defines a position for the offset; 0 represents starting from the beginning of the file, 1 represents starting from the current position, and 2 represents starting from the end of the file.
Return Value
If the operation is successful, it returns the new file position. If the operation fails, the function returns -1.
Example
The following example demonstrates the use of the seek() method:
Example
>>> f = open('workfile', 'rb+')
>>> 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 tutorialpro.txt is as follows:
1:www.tutorialpro.org
2:www.tutorialpro.org
3:www.tutorialpro.org
4:www.tutorialpro.org
5:www.tutorialpro.org
Loop through the content of the file:
Example
#!/usr/bin/python3
# Open file
fo = open("tutorialpro.txt", "r+")
print ("File name: ", fo.name)
line = fo.readline()
print ("Data read: %s" % (line))
# Reset file read pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print ("Data read: %s" % (line))
# Close file
fo.close()
The output of the above example is:
File name: tutorialpro.txt
Data read: 1:www.tutorialpro.org
Data read: 1:www.tutorialpro.org