原文链接:http://www.juzicode.com/archives/2745
错误提示:
读写文件时提示UnsupportedOperation: not readable
#juzicode.com/vx:桔子code
fileobj=open('example-r.txt','r')
cont = fileobj.read()
print(cont)
fileobj=open('example-w.txt','w')
cont = fileobj.read()
print(cont)
juzicode.com
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
<ipython-input-12-428692d8231a> in <module>
5
6 fileobj=open('example-w.txt','w')
----> 7 cont = fileobj.read()
8 print(cont)
UnsupportedOperation: not readable

可能原因:
1、打开example-w.txt是以只写方式打开的,再用read()方法读文件会报错。
解决方法:
1、如果文件只写入文件,不能使用read()方法。或者使用追加方式’a+’打开文件,可以先读文件,再写入文件。文件读写操作可参考:Python进阶教程m2–文件读写
#juzicode.com/vx:桔子code
with open('example-w.txt','a+',encoding='utf8') as fileobj:
posi = fileobj.tell() #获取当前文件指针位置
print('tell():',posi)
fileobj.seek(0) #文件指针指向开始位置
content=fileobj.read()
print('read():\n',content)
博客围绕Python读写文件时出现的UnsupportedOperation: not readable错误展开。指出可能原因是文件以只写方式打开却用read()方法读取。解决办法是若只写入则不使用read()方法,或用追加方式’a+’打开文件,可先读再写。
2355

被折叠的 条评论
为什么被折叠?



