Python中的seek函數 指針 使用教程
阿新 • • 發佈:2019-02-19
字符 foo bin utf fse 默認值 語法 python 取字符 file.seek(off, whence=0):
從文件中移動off個操作標記(文件指針),正往結束方向移動,負往開始方向移動。
如果設定了whence參數,就以whence設定的起始位為準,0代表從頭開始,1代表當前位置,2代表文件最末尾位置。
概述
seek() 方法用於移動文件讀取指針到指定位置。
語法
seek() 方法語法如下:
fileObject.seek(offset[, whence])
參數
offset -- 開始的偏移量,也就是代表需要移動偏移的字節數
whence:可選,默認值為 0。給offset參數一個定義,表示要從哪個位置開始偏移;0代表從文件開頭開始算起,1代表從當前位置開始算起,2代表從文件末尾算起
#!/usr/bin/python # -*- coding: utf-8 -*- # 文件定位測試 # 打開一個文件 fo = open("foo.txt", "r+") allstr = fo.read() print "全部內容:\n", allstr print "當前指針位置: ", fo.tell() print 35*"=" # 指針調到開始 position = fo.seek(0, 0) str = fo.read(3) print "讀取前三個字符串是:", str # 查找當前位置 position = fo.tell() print "當前指針位置: ", position print 35*"=" # 把指針再次重新定位到當前位置開始 position = fo.seek(2, 1) print "上一個指針移動2個,現在位置: ", fo.tell() a = fo.read(2) print "從指針位置讀取2個字符為: ", a print "當前指針位置: ", fo.tell() print 35*"=" # 把指針再次重新定位到從末尾開始 position = fo.seek(-3, 2) print "從末尾倒數3個,指針位置為: ", fo.tell() a = fo.read() print "從指針位置讀取字符串: ", a print "當前指針位置: ", fo.tell() # 關閉打開的文件 fo.close
foo.txt內容為:weiruoyu
輸出結果為:
全部內容:
weiruoyu
當前指針位置: 8
===================================
讀取前三個字符串是: wei
當前指針位置: 3
===================================
上一個指針移動2個,現在位置: 5
從指針位置讀取2個字符為: oy
當前指針位置: 7
===================================
從末尾倒數3個,指針位置為: 5
從指針位置讀取字符串: oyu
當前指針位置: 8
看明白上面的例子,就理解了。
Python中的seek函數 指針 使用教程