Python 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, that is, the number of bytes by which the offset needs to be moved
-
whence:Optional, with a default value of 0. The offset parameter defines where to start the offset from: 0 means counting 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 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+
"
)
"
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
Python File methods