python读写文件问题2

wenkebilly 2016-04-29 04:16:23
txt文本中的第一行为什么会覆盖?
源程序:
f = open(r'C:\python\Blowing in the wind.txt', 'r+')
f.seek(0,0)
f.writelines("Blowin' in the wind")
f.writelines('\40 Bob Dylan \n')
f.seek(0,2)
f.writelines('\n 1962 by Warner Bros. Inc')
f.seek(0,0)
print(f.read())
f.close()
运行前文件内容:
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
How many times must the cannon balls fly
Before they're forever banned
The answer my friend is blowing in the wind
The answer is blowing in the wind
运行后文件内容:
Blowin' in the wind Bob Dylan
wn
Before they call him a man
How many seas must a white dove sail
Before she sleeps in the sand
How many times must the cannon balls fly
Before they're forever banned
The answer my friend is blowing in the wind
The answer is blowing in the wind
1962 by Warner Bros. Inc
...全文
114 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
屎克螂 2016-05-03
  • 打赏
  • 举报
回复
因为你的想法和你的代码不一致。 如果你想追加内容到前面 你可以这样: data = open('xxx.txt').read() with open('xxx.txt', 'a') as f: f.write('aaa' + data)

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧