# 示例代码:处理 "No such file or directory" 错误
import os
def read_file(file_path):
try:
# 尝试打开文件
with open(file_path, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
# 如果文件不存在,捕获 FileNotFoundError 异常
print(f"Error: No such file or directory: '{file_path}'")
# 示例调用
file_path = 'non_existent_file.txt'
read_file(file_path)
os
模块,虽然在这个例子中没有直接使用,但通常处理文件路径时会用到。read_file
:该函数接收一个文件路径作为参数,并尝试读取文件内容。try-except
块来捕获 FileNotFoundError
异常。如果文件不存在,程序不会崩溃,而是打印一条错误信息。read_file
函数,以演示如何处理 "No such file or directory" 错误。上一篇:python sorted用法
下一篇:python 当前时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站