Python檔seek()方法

Python檔的seek()方法將檔的當前位置設置為偏移量(offset)。 whence參數是可選的,默認為0,表示絕對檔定位,其他值為1,這意味著相對於當前位置進行搜索,2表示相對於檔的結尾進行搜索。

seek()方法沒有返回值。 請注意,如果檔使用“a”或“a+”模式打開進行附加,則在下一次寫入時,任何seek()操作都將被撤銷。

如果僅使用’a‘在附加模式下打開該檔,該方法基本上是無操作的,但是對於在啟用讀取(模式’a+‘)的附加模式下打開的檔,該方法仍然有用。

如果使用’t‘以文本模式打開檔,則只有由tell()返回的偏移是合法的。使用其他偏移會導致未定義的行為。

語法

以下是seek()方法的語法 -

fileObject.seek(offset[, whence])

參數

  • offset − 這是檔中讀/寫指針的位置。
  • whence − 這是可選的,默認為0,表示絕對檔定位,其他值為1,這意味著相對於當前位置進行搜索,2表示相對於檔的末尾進行搜索。

返回值

  • 此方法不返回任何值。

示例

假設’foo.txt‘檔中包含以下行 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例顯示了seek()方法的用法。

#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "r+")
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

上一篇: Python檔對象方法 下一篇: Python os模組方法