seek() 方法設置 offset 為檔的當前偏移位置。在這裏參數是可選的,默認為0,這意味著絕對的檔定位,另外的一個值是1,這意味著尋求相對於當前位置,而值為2是設置尋找相對於檔的結束。
此方沒有返回值。請注意,如果檔被打開使用的是'a'或'A+'追加,任何seek()操作將在下次寫時撤銷。
如果該檔只打開使用 'A' 追加模式寫入,這種方法本質上是一個無操作,但是讀取啟用(模式'A+'),它在追加模式打開的檔非常有用。
如果檔在文本模式下使用“t”,只有 tell() 返回偏移開是合法的。其他偏移時會導致不確定的行為。
請注意,並非所有的檔對象都是可搜索。
語法
以下是 seek()方法的語法 -
fileObject.seek(offset[, whence])
參數
-
offset -- 這是在檔內的讀/寫指針的位置。
-
whence -- 這是可選的,默認為0表示絕對的檔定位;值是1時這意味著尋找相對於當前位置;以及值是2時尋找相對於檔的末尾。
返回值
此方法不返回任何值。
示例
下麵的示例顯示seek()方法的使用。
Assuming that 'foo.txt' file contains following text: This is 1st line This is 2nd line This is 3rd line This is 4th line This is 5th line
#!/usr/bin/python3 # Open a file fo = open("foo.txt", "rw+") print ("Name of the file: ", fo.name) line = fo.readlines() print ("Read Line: %s" % (line)) # Again set the pointer to the beginning fo.seek(0, 0) line = fo.readline() print ("Read Line: %s" % (line)) # Close opened file fo.close()
當我們運行上面的程式,會產生以下結果 -
Name of the file: foo.txt Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line'] Read Line: This is 1st line
上一篇:
Python3模組
下一篇:
Python3檔方法