YouTip LogoYouTip

File Seek

# Python2.x Python File seek() Method [![Image 3: Python File Methods](#) Python File Methods](#) * * * ### 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. * **whence:** Optional, default value is 0. Defines the starting point for the offset parameter: 0 represents the beginning of the file, 1 represents the current position, and 2 represents 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 readline() method: The content of the file .txt is as follows: 1:www. 2:www. 3:www. 4:www. 5:www. Loop to read the file content: ## Example #!/usr/bin/python# -*- coding: UTF-8 -*-# Open file fo = open(".txt", "rw+")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 of fo.seek(0, 0)line = fo.readline()print"The data read is: %s" % (line)# Close file fo.close() The output of the above example is: The file name is: .txt The data read is: 1:www. The data read is: 1:www. [![Image 4: Python File Methods](#) Python File Methods](#)
← File TruncateJavascript Json Stringify β†’