seek()方法在偏移設(shè)定該文件的當(dāng)前位置。參數(shù)是可選的,默認(rèn)為0,這意味著絕對(duì)的文件定位,它的值如果是1,這意味著尋求相對(duì)于當(dāng)前位置,2表示相對(duì)于文件的末尾。
沒有返回值。需要注意的是,如果該文件被打開或者使用'a'或'A+'追加,任何seek()操作將在下次寫撤消。
如果該文件只打開使用“a”的追加模式寫,這種方法本質(zhì)上是一個(gè)空操作,但讀使能(模式'a+'),它仍然在追加模式打開的文件非常有用。
如果該文件在文本模式下使用“t”,只有tell()返回的偏移開都是合法的。使用其他偏移會(huì)導(dǎo)致不確定的行為。
請(qǐng)注意,并非所有的文件對(duì)象都是可搜索。
語(yǔ)法
以下是seek()方法的語(yǔ)法:
fileObject.seek(offset[, whence])
參數(shù)
offset -- 這是在文件中,讀/寫指針的位置。 whence -- 這是可選的,默認(rèn)為0,這意味著絕對(duì)的文件定位,其它的值是1,這意味著尋求相對(duì)于當(dāng)前位置,2表示相對(duì)于文件的末尾。返回值
此方法不返回任何值。
例子
下面的例子顯示了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()
當(dāng)我們運(yùn)行上面的程序,它會(huì)產(chǎn)生以下結(jié)果:
Name of the file: foo.txtRead Line: This is 1st lineRead Line: This
|
新聞熱點(diǎn)
疑難解答
圖片精選