1. 程式人生 > >python3_檔案操作中file.seek()方法

python3_檔案操作中file.seek()方法

1、seek函式 

 file.seek(off, whence=0):從檔案中移動off個操作標記(檔案指標),正往結束方向移動,負往開始方向移動。

如果設定了whence引數,就以whence設定的起始位為準,0代表從頭開始,1代表當前位置,2代表檔案最末尾位置。

file.seek(0)是重新定位在檔案的第0位及開始位置
file = open("test.txt","rw") #注意這行的變動
file.seek(3) #定位到第3個 

2、示例

from sys import argv

script,input_file = argv

def print_all(f):
print f.read()

def rewind(f):
f.seek(0)

def print_a_line(line_count,f):
print line_count,f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind,kind of like a tape."

rewind(current_file)

print "Now let's print three lines."

current_line = 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

 

3、結果

 

其中test.txt內容如下:

 

this is the first line content typing in...
我是從鍵盤輸入的內容,準備寫入到檔案中.
這是第三行。
這是第四行。
這是第五行。


4、示例2

 

>>> f=open("aaa.txt","w") #以只寫的形式開啟一個叫做aaa.txt的檔案
>>> f.write("my name is liuxiang,i am come frome china") #寫入內容
>>> f.close() #關閉檔案
>>> f=open("aaa.txt","r") #以只讀開啟檔案
>>> f.read() #讀取內容
'my name is liuxiang,i am come frome china'
>>> f.seek(3,0) #“0”代表從檔案開頭開始偏移,偏移3個單位
>>> f.read(5) #從偏移之後的指標所指的位置(即“n”)開始讀取5個字元
'name '
>>> f.tell() #顯示現在指標指在哪個位置(即“i”的位置)
>>> f.readline() #讀取這一行剩下的內容
'is liuxiang,i am come frome china'

 

>>> f.seek(0,2) #“2”代表從末尾算起,“0”代表偏移0個單位
>>> f.read()
'' #因為是從末尾算起,內容已結束。所以讀取內容為空