Python3 File seek() Method
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
-
offset -- the starting offset, i.e. the number of bytes to move; if negative it means starting from that many positions from the end.
-
whence:Optional, default 0. It defines for offset where the offset starts from: 0 means from the beginning of the file, 1 means from the current position, and 2 means from the end of the file.
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+
"
)
(
"
File name:
"
,
fo
.
name
)
line
=
fo
.
readline
(
)
(
"
The data read is: %s
"
%
(
line
)
)
Reset the file read pointer to the beginning
fo
.
seek
(
0
,
0
)
line
=
fo
.
readline
(
)
(
"
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