运行以下代码会引起io.unsupportedeperation错误,因为该文件以"写"模式打开 -
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"不是错误吗?
io.unsupportederror在模块IO中找到。因此,在我们使用它之前,我们需要导入IO
import io
然后,当我们在尝试中测试错误时,我们可以使用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)