我想写一个文件,然后通过在文件的开头和结尾插入其他内容来修改它。你知道吗
我的代码:
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.
如何防止添加的内容覆盖原文的第一行?你知道吗
您可以阅读文件内容 数据=f.读取()
新数据=“开始”+数据+“结束”
你可以用“w”模式打开文件
f.写入(新数据)
相关问题 更多 >
编程相关推荐