Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python File seek() method

Python File seek() method

Python File methods Python File methods


Overview

seek() The method moves the file read pointer to a specified position.

Syntax

The seek() method syntax is as follows:



fileObject.seek(offset[, whence])

Parameters

Return Value

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

Example

The following example shows how to use the readline() method:

The contents of the runoob.txt file are as follows:



1:www.runoob.com

2:www.runoob.com

3:www.runoob.com

4:www.runoob.com

5:www.runoob.com

Read the file's contents in a loop:

Example

#!/usr/bin/python

-- coding: UTF-8 --

Opening a File

fo

=

open

(

"

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

)

Closing a File

fo

.

close

(

)

The output of the above example is:



文件名为:  runoob.txt

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



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

Python File methods Python File methods