python读写文件,如何将内容添加在文件开头呢

python读写文件,如何将内容添加在文件开头呢

somefile.txt已经有内容了
试过:
f.open("somefile.txt",'r+')
f.seek(0)
开始f.write(),因为是写入多行数据,就会覆盖掉原有文件的一部分
追加!

追加不行!这个问题我想当然了,经过测试确实如你描叙。

用f=open("somefile.txt",'a')也不行
因为我是通过循环,反复写入数据
seek( offset[, whence])

Set the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value. Note that if the file is opened for appending (mode 'a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode (mode 'a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). If the file is opened in text mode (mode 't'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
开头的只能重写
建个临时文件把追加行和源文件内容写入,然后在写回原文件应该可以吧?
其实读数据出来,重写肯定可以实现的。


对于你这个问题,我很奇怪,是个什么样的需求,才会有这样的实现和应用。
不知道楼主解决了没呢?


QUOTE:
原帖由 sunorr 于 2008-8-13 10:37 发表
不知道楼主解决了没呢?

汗。都这么老的尸体了。还挖上来。
当然解决了