這篇文章主要介紹了在Python中操作檔案之seek()方法的使用教程,是Python入門學習中的基礎知識,需要的朋友可以參考下
seek()方法在位移設定該檔案的當前位置。參數是可選的,預設為0,這意味著絕對的檔案定位,它的值如果是1,這意味著尋求相對於當前位置,2表示相對於檔案的末尾。
沒有傳回值。需要注意的是,如果該檔案被開啟或者使用'a'或'A+'追加,任何seek()操作將在下次寫撤消。
如果該檔案只開啟使用“a”的追加模式寫,這種方法本質上是一個空操作,但讀使能(模式'a+'),它仍然在追加模式開啟的檔案非常有用。
如果該檔案在文字模式下使用“t”,只有tell()返回的位移開都是合法的。使用其他位移會導致不確定的行為。
請注意,並非所有的檔案對象都是可搜尋。
文法
以下是seek()方法的文法:
fileObject.seek(offset[, whence])
參數
傳回值
此方法不返回任何值。
例子
下面的例子顯示了seek()方法的使用。
#!/usr/bin/python# Open a filefo = open("foo.txt", "rw+")print "Name of the file: ", fo.name# Assuming file has following 5 lines# This is 1st line# This is 2nd line# This is 3rd line# This is 4th line# This is 5th lineline = fo.readline()print "Read Line: %s" % (line)# Again set the pointer to the beginningfo.seek(0, 0)line = fo.readline()print "Read Line: %s" % (line)# Close opend filefo.close()
當我們運行上面的程式,它會產生以下結果:
Name of the file: foo.txtRead Line: This is 1st lineRead Line: This