Python读写文件的一个问题

本文探讨了Python中'r+'文件模式的使用限制及其引发的问题。当尝试在同一文件句柄上进行读写操作时,需要先定位文件指针,否则会遇到错误。文中提供了一个解决方法,即分别进行读写操作,并在两次操作间关闭文件。

读写模式中:'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 are
allowed (the file is said to be open for "update"). However, when you switch between
reading and writing, there must be an intervening fflushfsetposfseek, or rewind
operation. 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 text
f.seek(0)
f.write('haha')
f.close()
解决方案:

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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值