file.seek(offset[, whence])

Python3 File(文件) 方法 Python3 File(文件) 方法

概述

seek() 方法用于移动文件读取指针到指定位置。

语法

seek() 方法语法如下:

fileObject.seek(offset[, whence])

w♂©®3♂©®x♂©®u♂©®e.com提供本在线速查手册,请勿盗用!

参数

返回值

该函数没有返回值。

实例

以下实例演示了 readline() 方法的使用:

文件 W3xue.txt 的内容如下:

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

w♂©®3♂©®x♂©®u♂©®e.com提供本在线速查手册,请勿盗用!

循环读取文件的内容:

#!/usr/bin/python3

# 打开文件
fo = open("W3xue.txt", "r+")
print ("文件名为: ", fo.name)

line = fo.readline()
print ("读取的数据为: %s" % (line))

# 重新设置文件读取指针到开头
fo.seek(0, 0)
line = fo.readline()
print ("读取的数据为: %s" % (line))


# 关闭文件
fo.close()

w♂©®3♂©®x♂©®u♂©®e.com提供本在线速查手册,请勿盗用!

以上实例输出结果为:

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

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

w♂©®3♂©®x♂©®u♂©®e.com提供本在线速查手册,请勿盗用!

Python3 File(文件) 方法 Python3 File(文件) 方法