python3seek_Python3 file.seek()方法
此方?jīng)]有返回值。請(qǐng)注意,如果文件被打開(kāi)使用的是'a'或'A+'追加,任何seek()操作將在下次寫(xiě)時(shí)撤消。
如果該文件只打開(kāi)使用?'A'?追加模式寫(xiě)入,這種方法本質(zhì)上是一個(gè)無(wú)操作,但是讀取啟用(模式'A+'),它在追加模式打開(kāi)的文件非常有用。
如果文件在文本模式下使用“t”,只有?tell()?返回偏移開(kāi)是合法的。其他偏移時(shí)會(huì)導(dǎo)致不確定的行為。
請(qǐng)注意,并非所有的文件對(duì)象都是可搜索。
語(yǔ)法
以下是 seek()方法的語(yǔ)法?-
fileObject.seek(offset[, whence])
參數(shù)
offset?--?這是在文件內(nèi)的讀/寫(xiě)指針的位置。
whence?--?這是可選的,默認(rèn)為0表示絕對(duì)的文件定位;值是1時(shí)這意味著尋找相對(duì)于當(dāng)前位置;以及值是2時(shí)尋找相對(duì)于文件的末尾。
返回值
此方法不返回任何值。
示例
下面的示例顯示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()
當(dāng)我們運(yùn)行上面的程序,會(huì)產(chǎn)生以下結(jié)果?-
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
總結(jié)
以上是生活随笔為你收集整理的python3seek_Python3 file.seek()方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mongodb 备份mysql_Mong
- 下一篇: 特斯拉首批 V4 超充桩在荷兰投入使用: