Python的seek函数
生活随笔
收集整理的這篇文章主要介紹了
Python的seek函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
轉(zhuǎn)載自:?這里
Python中的seek函數(shù)作用是: 移動文件的讀取指針到指定位置。seek函數(shù)需要使用文件對象進行調(diào)用,無返回值。
seek函數(shù)有三種模式:
1) f.seek(p, 0) 或 f.seek(p)
將文件讀取指針移動到文件的第p個字節(jié)處,表示絕對位置。f.seek(0)移動到文件頭位置。
2) f.seek(p, 1)
在當(dāng)前位置的基礎(chǔ)上,將文件讀取指針移動p個字節(jié),表示相對位置。
3) f.seek(p, 2)
在文件尾的基礎(chǔ)上,將文件讀取指針移動p個字節(jié),表示相對位置。f.seek(0, 2)移動到文件尾位置。
代碼:
# --coding: utf-8 --#導(dǎo)入argv,并解包 from sys import argv script, filename = argv#函數(shù),輸出文件讀取指針的當(dāng)前位置 def print_current_position(f):print "Current position: ", f.tell()#函數(shù),輸出文件的當(dāng)前行 def print_current_line(f):print "Content of line: ", f.readline()f = open(filename, 'r'); #打開文件,并輸出全部內(nèi)容 print_current_position(f) print "Content of file: \n", f.read() print_current_position(f)f.seek(0, 0) #文件讀取指針回到起始位置 print_current_position(f) print_current_line(f) print_current_position(f)f.seek(3, 1) #文件讀取指針移動當(dāng)前位置之后的3個字節(jié) print_current_position(f) print_current_line(f) print_current_position(f)f.seek(0, 2) #文件讀取指針移動到文件尾部 print_current_position(f) print_current_line(f) print_current_position(f)f.close()
總結(jié)
以上是生活随笔為你收集整理的Python的seek函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机网络实验路由器,计算机网络路由器配
- 下一篇: Matpotlib绘图遇到时间刻度就犯难