免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 8605 | 回复: 8
打印 上一主题 下一主题

python读写文件,如何将内容添加在文件开头呢 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-24 14:25 |只看该作者 |倒序浏览
somefile.txt已经有内容了
试过:
f.open("somefile.txt",'r+')
f.seek(0)
开始f.write(),因为是写入多行数据,就会覆盖掉原有文件的一部分

论坛徽章:
0
2 [报告]
发表于 2008-04-24 14:45 |只看该作者
追加!

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

[ 本帖最后由 800long 于 2008-4-24 17:26 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2008-04-24 14:51 |只看该作者
用f=open("somefile.txt",'a')也不行
因为我是通过循环,反复写入数据

论坛徽章:
0
4 [报告]
发表于 2008-04-24 17:03 |只看该作者
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.

论坛徽章:
0
5 [报告]
发表于 2008-04-24 21:01 |只看该作者
开头的只能重写

论坛徽章:
0
6 [报告]
发表于 2008-04-24 21:24 |只看该作者
建个临时文件把追加行和源文件内容写入,然后在写回原文件应该可以吧?

论坛徽章:
0
7 [报告]
发表于 2008-04-25 09:42 |只看该作者
其实读数据出来,重写肯定可以实现的。


对于你这个问题,我很奇怪,是个什么样的需求,才会有这样的实现和应用。

论坛徽章:
0
8 [报告]
发表于 2008-08-13 10:37 |只看该作者
不知道楼主解决了没呢?

论坛徽章:
0
9 [报告]
发表于 2008-08-13 10:46 |只看该作者
原帖由 sunorr 于 2008-8-13 10:37 发表
不知道楼主解决了没呢?


汗。都这么老的尸体了。还挖上来。
当然解决了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP