Python File seek() Method

Python File(文件) 方法Python File Methods


Overview

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

Syntax

The syntax of the seek() method is as follows:

fileObject.seek(offset[, whence])

Parameters

  • offsetoffset -- The starting offset, i.e., the number of bytes to move.

  • whence:Optional, the default value is 0. Give a definition to the offset parameter, indicating where to start offsetting; 0 means starting from the beginning of the file, 1 means starting from the current position, 2 means starting from the end of the file.

Return Value

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

Example

The following example demonstrates the use of the readline() method:

The content of the file example.txt is as follows:

1:www.example.com
2:www.example.com
3:www.example.com
4:www.example.com
5:www.example.com

Loop to read the content of the file:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- # Open the file fo = open("example.txt", "rw+") print "File name:", 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 of the above example is:

文件名为:  example.txt
读取的数据为: 1:www.example.com

读取的数据为: 1:www.example.com

Python File(文件) 方法Python File Methods

Other Extensions