Python读写文件的一个问题

来源:互联网 发布:阿里云服务器部署项目 编辑:程序博客网 时间:2024/05/16 17:56

读写模式中:'r','w','r+'。 ‘r+’代表的是读写模式即可读可写吧?可是运行如下代码:

f= open('test.txt','r+')print f.read()f.write('hahaha')f.close()
出现错误提示   IOError: [Errno 0]

查到如下一段话:

When the "r+""w+"or "a+" access type is specified, both reading and writing areallowed (the file is said to be open for "update"). However, when you switch betweenreading and writing, there must be an intervening fflushfsetposfseek, or rewindoperation. The current position can be specified for the fsetpos or fseek operation,if desired.
使用seek方法后,不报错了。但是还是不能把结果write进去。
f = open('test.txt','r+')text= f.read()print textf.seek(0)f.write('haha')f.close()
解决方案:

读的时候打开,读完关闭。需要写的时候再重新打开,最后关闭。

我擦,好鸡肋的'r+'啊!


原创粉丝点击