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

Python3 File seek() Method

Python3 File seek() Method

Python3 File Methods Python3 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 seek() method:

Example

f

=

open

(

'workfile'

,

'rb+'

)

f.

write

(

b

'0123456789abcdef'

)

16

f.

seek

(

5

)

     

Move to the sixth byte of the file

5

f.

read

(

1

)

b

'5'

f.

seek

(

3

,

2

)

 

Move to the third byte from the end of the file

13

f.

read

(

1

)

b

'd'

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/python3

Opening a File

fo

=

open

(

"

runoob.txt

"

,

"

r+

"

)

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


Python3 File Methods Python3 File methods