Python File seek() 方法

Python File(文件) 方法 Python File(文件) 方法


概述

seek() 方法用于移動文件讀取指針到指定位置。

語法

seek() 方法語法如下:

fileObject.seek(offset[, whence])

參數(shù)

  • offset -- 開始的偏移量,也就是代表需要移動偏移的字節(jié)數(shù)

  • whence:可選,默認(rèn)值為 0。給offset參數(shù)一個(gè)定義,表示要從哪個(gè)位置開始偏移;0代表從文件開頭開始算起,1代表從當(dāng)前位置開始算起,2代表從文件末尾算起。

返回值

該函數(shù)沒有返回值。

實(shí)例

以下實(shí)例演示了 readline() 方法的使用:

文件 youj.txt 的內(nèi)容如下:

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

循環(huán)讀取文件的內(nèi)容:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打開文件
fo = open("youj.txt", "rw+")
print "文件名為: ", fo.name

line = fo.readline()
print "讀取的數(shù)據(jù)為: %s" % (line)

# 重新設(shè)置文件讀取指針到開頭
fo.seek(0, 0)
line = fo.readline()
print "讀取的數(shù)據(jù)為: %s" % (line)


# 關(guān)閉文件
fo.close()

以上實(shí)例輸出結(jié)果為:

文件名為:  youj.txt
讀取的數(shù)據(jù)為: 1:www.o2fo.com

讀取的數(shù)據(jù)為: 1:www.o2fo.com

Python File(文件) 方法 Python File(文件) 方法