避免在控制台中输出python异常(仅适用于单个情况)

时间:2019-02-21 23:48:08

标签: python python-3.x exception

当我打开文件且文件不在此处时-我只想显示一条错误消息“未找到文件”,而没有回溯和FileNotFoundError:

def print_file_content(filename):
try:
    with open(filename) as f:
        print("content of file", filename, ":")
        for i in f:
            print(i, end='')
except Exception:
    print("file %s not found" % filename)

控制台输出示例:

file receipt.txt not found
Traceback (most recent call last):
  File "./parse_and_json.py", line 48, in <module>
    receipt_objects = parse_receipt(FILENAME)
  File "./parse_and_json.py", line 29, in parse_receipt
    f = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'receipt.txt'

我也不希望仅退出或将stderr重定向为null(以后可能会有一些有用的信息)。我只想显示一条消息并继续程序的工作。如何实现(不太明显)?

0 个答案:

没有答案