简体   繁体   English

我将如何处理多个文件异常?

[英]How would i go about handling multiple file exceptions?

Basically i need to create a function that allows me to loads the basic details of a planned journey from a file. 基本上,我需要创建一个函数,该函数允许我从文件中加载计划行程的基本细节。 We are this brief: 我们很简短:

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. 返回值:3个字符串的字符串,其中包含从文件中读取的旅程的开始位置,结束位置和到达时间;如果失败,则返回(无,无,无)。

There are multiple test that all use magic numbers as inputs. 有多项测试,所有测试均使用幻数作为输入。 The tests are as follows: 测试如下:

This is the code for the bad data test should give you a example of one of the tests: 这是不良数据测试的代码,应为您提供以下测试之一的示例:

    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))

This is what i have so far, i am looking for help with this and any explanations would be fantastic! 到目前为止,这是我所拥有的,我正在寻求与此相关的帮助,任何解释都很棒!

My code atm: 我的代码atm:

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

The first failed test is because if the first or the second line is empty you bind a tuple with three None values to infomation and the next iteration then tries to append() something to that tuple – but tuples don't have an append() method. 第一次失败的测试是因为,如果第一行或第二行为空,则将具有三个None值的元组绑定到infomation ,然后进行下一次迭代,然后尝试append()某些内容append()到该tuple中-但是元组没有append()方法。 If you encounter an empty line you'll need to stop processing the lines and return the error value. 如果遇到空行,则需要停止处理这些行并返回错误值。

The second failed test is because you try to return infomation in the last line of you function, but if the file doesn't exist, there is no path of execution that assigns a value to this name. 第二个失败的测试是因为您尝试在函数的最后一行中返回infomation ,但是如果文件不存在,则没有执行路径可以为此名称分配值。

The third failure doesn't recognize that 13:60 isn't a valid time value. 第三次失败无法识别13:60不是有效的时间值。

The fourth failure returns two values instead of three, because you don't check if there are actually three lines, and not less, in the file. 第四个失败返回两个值,而不是三个值,因为您不检查文件中是否实际上存在三行而不是更少。

The sixths and last failure is because you wrap each single item in a list. 第六个也是最后一个失败是因为您将每个项目包装在列表中。 Why? 为什么?

A function passing all the test cases could look like this: 通过所有测试用例的函数可能如下所示:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我将如何 go 关于使用 python 制作“安全”.exe 文件? - How would I go about making a “Safe” .exe file with python? Python-我将如何去做? - Python - How would I go about doing this? 我将如何 go 关于将外部 python 文件中的功能添加到当前 python 文件? - How would I go about adding functions from external python file to current python file? 我将如何 go 关于实现多个输入 - 在 if 语句中 - 在 Python 中使用列表理解 - How would I go about achieving multiple inputs - within if statements - with list comprehension in Python 如何在大型文本文件中打印最后一行? - How would I go about printing the last line in a large text file? 我将如何从文本文档中制作设置文件? - How would i go about making a settings file out of a text document? 如何将基于python的文件转换器/解析器上传到网络? - How would I go about uploading a python based file converter/parser to the web? 我将如何 go 关于在 Python 中播放带声音的视频文件并设置播放 position? - How would I go about playing a video file with sound in Python and setting the play position? 我 go 如何为我的 discord 机器人令牌创建一个 .env 文件? - How would I go about creating an .env file for my discord bot token? 我该如何从提交的链接下载文件,然后重新上传到服务器进行流传输? - How would I go about downloading a file from a submitted link then reuploading to my server for streaming?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM