python写文件内容时出现io.UnsupportedOperation: not writable问题的解决方法

python写文件内容的代码是这样的

with open('./test.txt') as fo:
    fo.write('1672')
fo.close()

这时候运行代码就会出现下面的报错信息

        fo.write('1672')
io.UnsupportedOperation: not writable,字面翻译下很好理解,就是io流不支持写操作,看一下open()函数原型就清楚了。
open(file, mode=‘r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)

参数mode默认是‘r’只读模式,处理方法就是把model参数改成可写模式就行。

with open('./test.txt',mode='w') as fo:
    fo.write('1672')
fo.close()

附上mode参数列表

Character

Meaning

'r'

open for reading (default)

'w'

open for writing, truncating the file first

'x'

open for exclusive creation, failing if the file already exists

'a'

open for writing, appending to the end of file if it exists

'b'

binary mode

't'

text mode (default)

'+'

open for updating (reading and writing)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值