<1>獲取當前讀寫的位置
在讀寫文件的過程中,如果想知道當前的位置,可以使用tell()來獲取
#打開或創建一個文件
f = open('./test.txt', 'r')
str = f.read(3)
print('讀取的數據是:', str)
#查找當前位置
position = f.tell()
print('當前文件的讀寫位置是: ', position)
f.close()
<2>定位到某個位置
如果在讀寫文件的過程中,需要從另外一個位置進行操作的話,則用seek()
seek(offset, from)有2個參數
- offset:偏移量
- from:方向
- 0:表示文件開頭
- 1:表示當前位置
- 2:表示文件末尾
demo:把位置設置為:從文件開頭,偏移5個字節
#打開一個已存在的文件
f = open('./test.txt', 'r')
str = f.read(30)
print('讀取的數據是:', str)
#查找當前位置
position = f.tell()
print("當前文件位置:', position)
#重新設置位置
f.seek(5,0)
#查找當前位置
position = f.tell()
print("當前文件位置:', position)
f.close()
demo:把位置設置為:離文件末尾,3字節處
#打開一個已存在的文件
f = open('./test.txt', 'r')
#查找當前位置
position = f.tell()
print('當前位置:', position)
#重新設置位置
f.seek(-3,2)
#讀取到的數據為:文件最后3個字節數據
str = f.read()
print('讀取的數據是:', str)
f.close()