在 Python 中查詢檔案位置
tell() 方法告訴您文字檔案中的當前位置;換句話說,下一次讀取或寫入將從文字檔案的開頭開始這麼多位元組。
seek(offset[, from]) 方法更改當前文字檔案位置。offset 引數指示要移動的位元組數。from 引數指定移動位元組的參考位置。
如果 from 設定為 0,則表示使用文字檔案的開頭作為參考位置,1 表示使用當前位置作為參考位置,如果將它設定為 2,則文字檔案的結尾將被用作參考位置。
示例
讓我們使用上面建立的 foo.txt 文字檔案。
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str
# Check current position
position = fo.tell()
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()這將產生以下結果 −
Read String is : Python is Current file position : 10 Again read String is : Python is
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP