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)

你可能感兴趣的:(python,开发语言)