2017-07-28 45 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

相关问题