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()
'' #因為是從末尾算起,內容已結束。所以讀取內容為空