Overview
The Python file Seek () method is used to move the file read pointer to the specified location.
Grammar
The Seek () method syntax is as follows:
Fileobject.seek (Offset[,whence])
Parameters
such as "Lu Fei Learning City" with GBK is 2 bytes A word, with Utf-8 is 3 bytes, so when opened with GBK, Seek (4) the cursor to the "Fly" and "learn" the middle of two words.
But if it is Utf8,seek (4) will lead to, get the word fly part of the byte, printed words will be error, because processing the remainder of the text found with UTF8 can't handle, because the code is not up. A byte is missing.
whence: optional, default value is 0. Indicates from which position to start the offset; 0 represents starting at the beginning of the file, 1 representing starting at the current position, and 2 representing the end of the file.
return value
The function does not return a value.
Instance
The following example demonstrates the use of the Seek () method:
The contents of the file Runoob.txt are as follows:
1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com
To iterate through the contents of a file:
#!/usr/bin/python3# Open File fo = open ("Runoob.txt", "r+", encoding= "Utf-8") print ("File name:", fo.name) line = Fo.readline () Print ("Read data:%s"% (line)) # Reset file read pointer to start Fo.seek (0,0) line = Fo.readline () print ("Read data:%s"% (line)) # Close file Fo.close ()
The result of the above example output is:
The file name is: Runoob.txt reads the data: 1:www.runoob.com reads: 1:www.runoob.com
Python file Seek () method