引出問題
或許有的小白不知道這個文件指針就會出現以下問題:
案例一:
代碼含義:寫入三句話,並調用兩次read()函數讀取兩次文本
file = open("C:\\try.txt",'w',encoding="utf-8")
file.write("I'm the first row.\n")
file.write("I'm the second row.\n")
file.write("I'm the third row.\n")
file.close()
file=open("C:\\try.txt",'r',encoding="utf-8")
print("第一眼")
print(file.read())
print("第二眼")
print(file.read())
file.close()
print("程序執行完畢")
'''
運行結果:
第一眼
I'm the first row.
I'm the second row.
I'm the third row.
第二眼
程序執行完畢
'''
案例二:
代碼含義,統計文本行數以及單詞有多少個及單詞出現的次數
with open("C:\\try.txt",'r+',encoding="utf-8") as f:
f.write("I'm the first row.\n")
f.write("I'm the second row.\n")
f.write("I'm the third row.\n")
line=f.read().count("\n")
print("行數是:", line)
print("單詞的個數是:", line + f.read().count(" "))
word=f.read().replace("\n", " ").replace(".","").split(" ")
word.pop()
dic={}
for i in word:
dic[i]=[word.count(i)]
print(dic)
'''
運行結果:
行數是: 0
單詞的個數是: 0
{}
'''
提出問題:咦!爲什麼都沒有成功呢?其實代碼是對的,就是忽略了文件的指針,這兩個案例都是同一個問題,那到底是什麼因素導致我們無法二次讀取呢?
這是因爲python讀取文本採用了文本指針,指針在哪就在哪寫,指針在哪,你就只能讀取指針後面的東西。
舉個例子
注意:這個文件中寫入的還是案例一,寫入進去的三句話。
file=open("C:\\try.txt",'r',encoding="utf-8")
print(file.read(1))
print(file.read(2))
print(file.read(3))
'''
運行結果:
I
'm
th
'''
結論:可以看到第一個read()裏面的參數是1,表示讀取指針後面一個元素,讀取完,指針後移動一位,第二個read()裏面的參數是2,表示讀取指針後面的兩個元素,讀取完,指針後移動兩位等等,以此類推。這就爲什麼能解釋爲什麼案例一與案例二的問題了,讀取完或者寫完,指針都在文本的結尾處了,無論你做什麼操作,都無法查看。
解決問題
那麼我們知道原因的所在了,引出今天的正題!!!
seek()函數設置光標的位置
tell()函數獲取文件的指針位置
使用seek()設置指針的位置,以便重新讀取
seek(x,y)裏面有兩個參數
x代表從文件開頭的第幾個字節位置開始讀取
y有三個選項,主要是以什麼爲參考點,來進行指針移動的。
(1)0
表示絕對位置(文件的開頭位置),如果不選第二個參數,默認爲0。
(2)1
表示相對位置(光標的當前位置)。
(3)2
表示光標在文件的末尾,可以從文件的末尾,移動幾個位置後開始讀。
注意:x都可以是負數,要不在y爲2的時候用正數當然會報錯,所以得用負數。
案例一:使用seek()與tell()函數後的效果
file = open("C:\\try.txt", 'w', encoding="utf-8")
file.write("I'm the first row.\n")
file.write("I'm the second row.\n")
file.write("I'm the third row.\n")
file.close()
file = open("C:\\try.txt", 'r', encoding="utf-8")
print("第一眼")
print(file.read())
print("指針的位置:", file.tell())
file.seek(0)
print("指針的位置:", file.tell())
print("第二眼")
print(file.read())
file.close()
'''
運行結果:
第一眼
I'm the first row.
I'm the second row.
I'm the third row.
指針的位置: 61
指針的位置: 0
第二眼
I'm the first row.
I'm the second row.
I'm the third row.
'''
結論:二次讀取成功,說明我們之前的分析正確。
那麼我們也試試把seek()函數加入到第二個案例裏吧!
案例二:使用seek()函數後的效果。
with open("C:\\try.txt", 'r+', encoding="utf-8") as f:
f.write("I'm the first row.\n")
f.write("I'm the second row.\n")
f.write("I'm the third row.\n")
f.seek(0)
line = f.read().count("\n")
print("行數是:", line)
f.seek(0)
print("單詞的個數是:", line + f.read().count(" "))
f.seek(0)
word = f.read().replace("\n", " ").replace(".", "").split(" ")
word.pop()
dic = {}
for i in word:
dic[i] = [word.count(i)]
print(dic)
'''
運行結果:
行數是: 3
單詞的個數是: 12
{"I'm": [3], 'the': [3], 'first': [1], 'row': [3], 'second': [1], 'third': [1]}
'''
來一波,推送吧!
羣號:781121386
羣名:人生苦短,我學編程
歡迎大家加入我們,一起交流技術!!!