python not readable_Python错误集锦:读写文件时提示UnsupportedOperation: not readable

时间: 2023-07-29 admin 互联网

python not readable_Python错误集锦:读写文件时提示UnsupportedOperation: not readable

python not readable_Python错误集锦:读写文件时提示UnsupportedOperation: not readable

错误提示:

读写文件时提示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)

in

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)

关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识