运行以下代码将引发io.UnsupportedOperation错误,因为该文件是以“写入”模式打开的-
with open("hi.txt", "w") as f:
print(f.read())输出为-
io.UnsupportedOperation: not readable所以,我们可以通过这样做来掩盖这一点-
try:
with open("hi.txt", "w") as f:
print(f.read())
except io.UnsupportedOperation:
print("Please give the file read permission")输出-
NameError: name 'io' is not defined甚至去掉了“io”吐出了同样的错误-
try:
with open("hi.txt", "w") as f:
print(f.read())
except UnsupportedOperation:
print("Please give the file read permission")输出-
NameError: name 'UnsupportedOperation' is not defined为什么它不起作用?"io.UnsupportedOperation“不是一个错误吗?
发布于 2019-05-25 22:08:50
可以在模块io中找到io.UnsupportedError。因此,在使用它之前,我们需要导入io。
import io
然后,当我们测试try except子句中的错误时,我们可以使用io.UnsupportedError。这为我们提供了:
import io
try:
with open("hi.txt", "w") as f:
print(f.read())
except io.UnsupportedOperation as e:
print(e)或者如果你只使用io模块来检查这个特定的错误。
from io import UnsupportedError
try:
with open("hi.txt", "w") as f:
print(f.read())
except UnsupportedOperation as e:
print(e)https://stackoverflow.com/questions/56305530
复制相似问题