如何在文本文件的开头插入内容?

时间:2017-07-28 19:00:55

标签: python

我想写一个文件,然后通过在文件的开头和结尾插入一些其他内容来修改它。

我的代码:

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.

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

1 个答案:

答案 0 :(得分:0)

您可以阅读文件内容 data = f.read()

new_data =" start" +数据+"结束"

您可以用' w'打开文件。模式并执行

f.write(NEW_DATA)