2015-10-16 50 views
0

這一計劃的目的是在數據文件中,以退格三次:如何用python中的文件句柄修改文件後在文件上寫入?

ofile = open(myfile, 'r') 
file = open(myfile, 'r') 

with open(myfile, 'rb+') as filehandle: 
    filehandle.seek(-3, os.SEEK_END) 
    filehandle.truncate() 

然後我試圖通過切換到「寫」功能後,此添加額外的文本:

ofile = open(myfile, 'r') 
file = open(myfile, 'r') 

with open(myfile, 'rb+') as filehandle: 
    filehandle.seek(-3, os.SEEK_END) 
    filehandle.truncate() 

ofile = open(myfile, 'w') 

ofile.write('*') 

這但是,會覆蓋整個數據集並在空白文檔上只寫入「*」。如何在不刪除剩餘內容的情況下添加文件?

回答

1

您需要使用append標誌而不是寫入。所以,ofile = open(myfile, 'a')