2017-07-28 95 views
0

我想寫一個文件,然後通過在文件的開頭和結尾插入一些其他內容來修改它。如何在文本文件的開頭插入內容?

我的代碼:

f = open('Blowing in the wind.txt', 'w+') 
f.seek(0) 
f.truncate() 
f.write(''' 
How many roads must a man walk down 

Before they call him a man 

How many seas must a white dove sail 

Before she sleeps in the sand 
''') 
content= f.read() 
f.seek(0) 
f.write('Blowing in the wind\n' + 'Bob\n'+content) 
f.seek(0,2) 
f.write('\n1962 by Warner Bros.Inc.') 
f.seek(0,0) 
txt= f.read() 
print(txt) 

結果:

Blowing in the wind 
Bob 
n walk down 

Before they call him a man 

How many seas must a white dove sail 

Before she sleeps in the sand 

1962 by Warner Bros.Inc. 

如何防止覆蓋原始文本的第一行添加的內容?

+0

檢查此[post](https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – PRMoureu

回答

0

您可以讀取文件內容 數據= f.read()

NEW_DATA = 「開始」 +數據+ 「端」

您可以打開文件與 'W' 模式,並做

f.write(new_data)

+0

嗨,我讀了幫助文件,我認爲W +可以做所有的事情?所以我假設可以使用w +而不是w? –

+0

而且當我嘗試使用「a +」打開文件時,即使我將指針移至seek(0)的開始處,附加文本仍附加在原始文件的末尾,爲什麼會這樣? –

+0

您需要有兩個文件實例,一個使用'r'模式,另一個使用'w +'模式 – rkatkam

相關問題