Python 如何处理多个文件异常?

Python 如何处理多个文件异常?,python,python-3.x,exception,Python,Python 3.x,Exception,基本上,我需要创建一个函数,允许我从文件中加载计划行程的基本细节。我们谨此陈辞: 参数:包含文件路径的字符串 返回:一个三元组字符串,包含从文件读取的旅程的开始位置、结束位置和到达时间,如果失败,返回(无、无、无) 有多个测试都使用幻数作为输入。测试如下: 这是坏数据测试的代码,应为您提供以下测试之一的示例: PATH = os.path.expanduser('~/test_prev_plan_spec.txt') def test_missing_file_is_handl

基本上,我需要创建一个函数,允许我从文件中加载计划行程的基本细节。我们谨此陈辞:

参数:包含文件路径的字符串

返回:一个三元组字符串,包含从文件读取的旅程的开始位置、结束位置和到达时间,如果失败,返回(无、无、无)

有多个测试都使用幻数作为输入。测试如下:

这是坏数据测试的代码,应为您提供以下测试之一的示例:

    PATH = os.path.expanduser('~/test_prev_plan_spec.txt')

    def test_missing_file_is_handled(self):
        if os.path.exists(self.PATH):
            os.unlink(self.PATH)
        plan = utils.load_prev_plan_spec(self.PATH)
        self.assertEqual(3, len(plan))
        self.assertEqual(plan, (None, None, None))

    def test_spec_loads_ok(self):
        from_ = 'Bournemouth'
        to = 'Southampton'
        arrive_at = '2019/04/20 13:30'
        with open(self.PATH, 'wt') as f:
            f.write('{}\n{}\n{}\n'.format(from_, to, arrive_at))
        plan = utils.load_prev_plan_spec(self.PATH)
        self.assertEqual(3, len(plan))
        self.assertEqual(from_, plan[0])
        self.assertEqual(to, plan[1])
        self.assertEqual(arrive_at, plan[2])

    def test_short_spec_is_ignored(self):
        from_ = 'Bournemouth'
        to = 'Southampton'
        with open(self.PATH, 'wt') as f:
            f.write('{}\n{}\n'.format(from_, to))
        plan = utils.load_prev_plan_spec(self.PATH)
        self.assertEqual(3, len(plan))
        self.assertEqual(plan, (None, None, None))

        with open(self.PATH, 'wt') as f:
            f.write('{}\n'.format(from_))
        plan = utils.load_prev_plan_spec(self.PATH)
        self.assertEqual(3, len(plan))
        self.assertEqual(plan, (None, None, None))

    def test_empty_line_is_handled(self):
        from_ = 'Bournemouth'
        to = ''
        arrive_at = '2019/04/20 13:30'
        with open(self.PATH, 'wt') as f:
            f.write('{}\n{}\n{}\n'.format(from_, to, arrive_at))
        plan = utils.load_prev_plan_spec(self.PATH)
        self.assertEqual(3, len(plan))
        self.assertEqual(plan, (None, None, None))

    def test_bad_data_line_is_handled(self):
        from_ = 'Bournemouth'
        to = 'Southampton'
        arrive_at = '2019/04/20 13:60'
        with open(self.PATH, 'wt') as f:
            f.write('{}\n{}\n{}\n'.format(from_, to, arrive_at))
        plan = utils.load_prev_plan_spec(self.PATH)
        self.assertEqual(3, len(plan))
        self.assertEqual(plan, (None, None, None))
这就是我到目前为止所拥有的,我正在寻求帮助,任何解释都会很棒

我的自动取款机代码:

def load_prev_plan_spec(PATH):
    '''
    Function: utils.load_prev_plan_specLoads the basic details of a planned journey from a file.
    Parameters: A string containing a file path
    Returns: A 3-tuple of strings containing start location, end location and arrival time of a journey
    read from the file, or (None, None, None) if unsuccessful.
    '''


    try:
        if os.path.exists(PATH):
            infomation = []
            f = open(PATH, 'r', encoding='cp1252')
            for line in f:
                infomation.append([line.strip()])
                if not line.strip():
                    infomation = (None, None, None)
            tuple(infomation)
            f.close()
            return infomation
        else:
            pass
    except IOError as err2:
        print(err2)
        raise IOError
    else:
        return infomation


第一个失败的测试是因为如果第一行或第二行为空,您将一个具有三个
None
值的元组绑定到
information
,然后下一次迭代尝试向该元组添加
append()
内容,但元组没有
append()
方法。如果遇到空行,则需要停止处理这些行并返回错误值

第二个失败的测试是因为您试图在函数的最后一行返回
information
,但如果文件不存在,则没有为该名称赋值的执行路径

第三个故障未识别出
13:60
不是有效的时间值

第四个失败返回两个值而不是三个值,因为您不检查文件中是否实际有三行,而不是更少

第六个也是最后一个失败是因为您将每个项目都包装在一个列表中。为什么?

通过所有测试用例的函数可能如下所示:

from datetime import datetime as DateTime


def load_prev_plan_spec(path):
    try:
        with open(path, 'r', encoding='cp1252') as file:
            lines = [line.strip() for line in file]
            if len(lines) == 3 and all(lines):
                try:
                    # 
                    # Just for the `ValueError` to test if string is a valid 
                    # timestamp.
                    # 
                    DateTime.strptime(lines[-1], '%Y/%m/%d %H:%M')
                except ValueError:
                    pass  # Intentionally ignored.
                else:
                    return tuple(lines)
    except (OSError, UnicodeDecodeError):
        pass  # Intentionally ignored.

    return (None, None, None)

第一个失败的测试是因为如果第一行或第二行为空,您将一个具有三个
None
值的元组绑定到
information
,然后下一次迭代尝试向该元组添加
append()
内容,但元组没有
append()
方法。如果遇到空行,则需要停止处理这些行并返回错误值

第二个失败的测试是因为您试图在函数的最后一行返回
information
,但如果文件不存在,则没有为该名称赋值的执行路径

第三个故障未识别出
13:60
不是有效的时间值

第四个失败返回两个值而不是三个值,因为您不检查文件中是否实际有三行,而不是更少

第六个也是最后一个失败是因为您将每个项目都包装在一个列表中。为什么?

通过所有测试用例的函数可能如下所示:

from datetime import datetime as DateTime


def load_prev_plan_spec(path):
    try:
        with open(path, 'r', encoding='cp1252') as file:
            lines = [line.strip() for line in file]
            if len(lines) == 3 and all(lines):
                try:
                    # 
                    # Just for the `ValueError` to test if string is a valid 
                    # timestamp.
                    # 
                    DateTime.strptime(lines[-1], '%Y/%m/%d %H:%M')
                except ValueError:
                    pass  # Intentionally ignored.
                else:
                    return tuple(lines)
    except (OSError, UnicodeDecodeError):
        pass  # Intentionally ignored.

    return (None, None, None)

不清楚你到底在问什么。你想做什么也不完全清楚。通常,您应该提供一个简明的问题工作示例,并告诉我们您尝试了什么。如果您只是询问如何处理异常,请阅读。然后,阅读文档,了解您使用的方法可能引发哪些异常,可能会添加一些自定义异常,并使用
try except
进行处理。不清楚您实际上在问什么。你想做什么也不完全清楚。通常,您应该提供一个简明的问题工作示例,并告诉我们您尝试了什么。如果您只是询问如何处理异常,请阅读。然后,阅读文档,了解您使用的方法可能引发的异常,可能添加一些自定义异常,并使用
try except
进行处理。