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 |
---|---|
|
open for reading (default) |
|
open for writing, truncating the file first |
|
open for exclusive creation, failing if the file already exists |
|
open for writing, appending to the end of file if it exists |
|
binary mode |
|
text mode (default) |
|
open for updating (reading and writing) |