python - 找不到文件怎么显示?
问题描述
我在 Python 3.6 中使用它:
filetest="test.txt"
with open(filetest,"r") as file:
如果未检测到 filetest 上的输入,我应该如何让 Python 控制台将“文件不可用”显示为输出?(比如目录下没有test.txt)
解决方案
您可以将其包装在一个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
异常。
推荐阅读
- sql - 根据类组计算不同的记录并且不应有重复
- sql-server - 无法使用 Teiid 在 SQL Server 的 datetimeoffset 列中插入空值
- amazon-web-services - Amazon SES:将电子邮件写入按日期命名的文件夹中的 S3?
- html - HTML 描述列表
- CSV Bash 工具
- java - ';' 预期的。在 Android Studio 的幻灯片中添加标题、描述和图像时出现意外令牌
- angular - 更改字体后材料输入标签无法正确显示
- python - 另一台 PC 上没有名为 XXX 的模块
- python-3.x - 使用漂亮的汤或硒从网站上抓取所有链接
- c# - AdornerLayer.Update 方法之间的区别
- reactjs - 在加载 React 应用程序时读取请求标头