English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python File seek() Usage and Example

Python File (File) Methods

Overview

seek() This method is used to move the file read pointer to the specified position.

Syntax

The syntax of seek() method is as follows:

fileObject.seek(offset[, whence])

parameter

  • 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.

Return value

If the operation is successful, the new file position is returned, and if the operation fails, the function returns -1.

Example

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:

Online examples

# 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

Python File (File) Methods