鍍金池/ 問答/Python/ .write()后,seek(0)&'a+' 的文件指針問題

.write()后,seek(0)&'a+' 的文件指針問題

我的代碼問題:

 1 from sys import argv
 2
 3 script,filename=argv
 4 
 5 line1=input('type someother code:'+'\n'+'>')
 6 line2=input('please type some code:'+'\n'+'>')
 7 line3=input('please append some code:'+'\n'+'>')
 8 t1=open(filename,'w+')
 9 t1.write(line1+'\n')
10 t1.write(line2+'\n')
11    #此行我第二次加入一句t1.seek(0),程序就一切如預(yù)期了,不解。。。
12 t0=open(filename,'a+')
13 t0.write(line3)
14 t0.seek(0)
15 print('The Final result:\n%s'%t0.read())
16
17 t1.close
18 t0.close

運(yùn)行結(jié)果:>py testing.py test.txt

type someother code:
.>>>this line 1
please type some code:
.>>>this is line 2
please append some code:
.>>>this is append line
The Final result:
this is append line

testing.txt 寫入文件內(nèi)容:

this is line 1
this is line 2

很奇怪~ 最后一行this is append line沒有寫入文件,而print(t0.read())卻只打印出最后一行?


我胡亂試,偶爾在第11行加入了一條t1.seek(0)后,一切如我預(yù)期了(print正常打印出testing.txt的全部內(nèi)容了,testing.txt也被正常寫入了三條input(str))

雖然代碼通過了,但是原因我還是不懂~求教

t1.seek(0) 作用是將指針移回文件開頭,我在第14行寫它是因?yàn)榻酉聛砦乙猵rint全部文件內(nèi)容,而write后,指針指向了文件尾部,此時read只能讀出空。 但12行我在文件末尾用'a+'模式追加一句str,文件指針指向哪應(yīng)該都無所謂?。?a+'模式不是強(qiáng)行在文件尾部添加str嘛?為什么出錯?? 而我在12行前加一句t1.seek(0)就OK了~ 實(shí)在不解。
回答
編輯回答
蔚藍(lán)色

其實(shí)最好是寫完關(guān)掉,再打開追加, 或者至少flush一下緩沖區(qū),猜測是因?yàn)椴煌膐pen, 會建立不同的緩沖區(qū), 這樣對同一個文件操作,會對文件內(nèi)容意外覆蓋

from sys import argv
script,filename=argv

line1=input('type someother code:'+'\n'+'>')
line2=input('please type some code:'+'\n'+'>')
line3=input('please append some code:'+'\n'+'>')
t1=open(filename,'w+')
t1.write(line1+'\n')
t1.write(line2+'\n')
t1.flush()
t1.close()

t0=open(filename,'a+')
t0.write(line3)
t0.flush()
t0.seek(0)
print('The Final result:\n%s'%t0.read())
t0.close()
2017年3月16日 12:25
編輯回答
拽很帥

我試驗(yàn)了一下,大概明白了為什么。你也可以在代碼中用f.tell()來監(jiān)測指針的位置。
按照我的理解,你的t1以“w+”的模式打開了一個文件filename,t1的指針在文件的開頭,然后進(jìn)行了一系列write操作。但是要注意,此時數(shù)據(jù)只是寫入了一個緩存區(qū),并沒有真正寫入filename。
接著以“a+”的模式打開了一個t0,它的指針在文件的結(jié)尾(最初的filename的結(jié)尾),所以對t0進(jìn)行write操作也是從t0的指針位置開始的。這么一說不知你明白了沒有

2017年1月16日 21:07