python seek(0)_seek() 方法
https://www.xin3721.com/eschool/pythonxin3721/
用于移動文件的讀取指針到指定位置
seek() 方法語法如下:
fileObject.seek(offset[,whence])
參數
offset --偏移量,也就是代表需要移動偏移的字節數
whence:可選,默認值為 0。表示要從哪個位置開始偏移;0代表從文件開頭開始算起,1代表從當前位置開始算起,2代表從文件末尾算起。
如
with open("writeline.txt") as file2:
file2.seek(2)
print(file2.read())
truncate() 方法
用于截斷文件并返回截斷的字節長度
指定長度的話,就從文件的開頭開始截斷指定長度,其余內容刪除;不指定長度的話,就從文件開頭開始截斷到當前位置,其余內容刪除
可以用seek()方法,把指針定位到指定位置。
如
with open("newfile1.txt","r+") as file1:
file1.truncate(5)
with open("newfile1.txt") as file1:
print(file1.read())
with open("seek.txt","r+",encoding="gbk") as file1:
file1.seek(16)
file1.truncate()
file1.seek(0)
print(file1.read())
Tell方法
返回文件指針的當前位置
如
with open("writeline.txt","r") as file2:
print(file2.read())
print(file2.tell())
file2.close()
next() 方法
ython 3 中的 文件 對象不支持?next()?方法。 Python 3 的內置函數 next() 通過迭代器調用 __next__() 方法返回下一項。 在循環中,
next()方法會在每次循環中調用,該方法返回文件的下一行,如果到達結尾(EOF),則觸發?StopIteration
如:
with open("china.txt","r",encoding="gbk") as file1:
num=len(file1.readlines())
file1.seek(0,0)
for index in range(num):
line = next(file1)
print ("第 %d 行 內容: %s" % (index, line))
總結
以上是生活随笔為你收集整理的python seek(0)_seek() 方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [置顶]《游戏引擎架构》信息总汇
- 下一篇: P4939 Agent2