English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
seek() This method is used to move the file read pointer to the specified position.
The syntax of seek() method is as follows:
fileObject.seek(offset[, whence])
offset -- The starting offset, which is the number of bytes to move
whence:Optional, the default value is 0. Define an offset parameter to indicate from which position to start the offset; 0 represents starting from the beginning of the file.1Represents the number of bytes from the current position.2Represents the number of bytes from the end of the file.
If the operation is successful, the new file position is returned, and if the operation fails, the function returns -1.
The following example demonstrates the use of the readline() method:
File w3The content of codebox.txt is as follows:
1:fr.oldtoolbag.com 2:fr.oldtoolbag.com 3:fr.oldtoolbag.com 4:fr.oldtoolbag.com 5:fr.oldtoolbag.com
Loop to read the content of the file:
# Open the file fo = open("w3codebox.txt, "r") print("The file name is: ", fo.name) line = fo.readline() print("The data read is: %s" % (line)) # Reset the file read pointer to the beginning fo.seek(0, 0) line = fo.readline() print("The data read is: %s" % (line)) # Close the file fo.close()
The output result of the above example is:
The file name is: w3codebox.txt The data read is: 1:fr.oldtoolbag.com The data read is: 1:fr.oldtoolbag.com