有很多类似的文件的I/O问题,最近..
总之,你需要创建一个新的文件
- 第一,编写新线将文件
- 读取线从旧文件,并将其写入文件
如果你能保证你的每一个新行添加到开始较长不是每一个相应的原始行开头的,你可以做到这一点的地方:
f = open('file.txt','r+')
lines = f.readlines() # read old content
f.seek(0) # go back to the beginning of the file
f.write(new_content) # write new content at the beginning
for line in lines: # write old content after new
f.write(line)
f.close()
上面的例子寻找它后,它的整体中的所有数据写入的位置在文件的开始,因为文件的内容是用新内容覆盖。
否则你需要写一个新的文件
f = open('file.txt','r')
newf = open('newfile.txt','w')
lines = f.readlines() # read old content
newf.write(new_content) # write new content at the beginning
for line in lines: # write old content after new
newf.write(line)
newf.close()
f.close()
见http://stackoverflow.com/questions/4454298/prepend-a-line-to-an-existing-file-in-蟒蛇 –
我宁愿看到,已经做了一些努力,在通过stackoverflow搜索类似的问题以前问及为什么那里的答案不能满足您的问题。我们经常看到重复的问题。因为我们没有前进,所以这对SO或社区并不是好事。 – pyfunc
@pyfunc,从这个系统这里,搜索功能超时。没有其他系统可以用于搜索。我已经把这个,我自己的问题作为Exact Dupe的近距离投票标记出来,并且已经在评论中张贴了这个链接,任何人都可以这样做。 (系统不会让我删除) –