首页 > 解决方案 > 找不到文件怎么显示?

问题描述

我在 Python 3.6 中使用它:

filetest="test.txt"
with open(filetest,"r") as file:

如果未检测到 filetest 上的输入,我应该如何让 Python 控制台将“文件不可用”显示为输出?(比如目录下没有test.txt)

标签: pythonpython-3.x

解决方案


您可以将其包装在一个try-except块中,如果没有名为“test.txt”的文件,那么您将打印消息:“文件不可用”。

一个简单的例子是:

filename="test.txt"
try:
    with open(filetest,"r") as file:
        pass
except OSError as e:
    print("File not available")
    print(e.strerror)

我添加了,OSError因为它表明文件处理存在问题,您可以在以下链接中阅读:https ://docs.python.org/3/library/exceptions.html

也可以使用FileNotFoundError异常。


推荐阅读