【问题标题】:How do I make an exception for an incorrect file type [closed]如何对不正确的文件类型进行例外处理[关闭]
【发布时间】:2022-11-14 01:44:05
【问题描述】:

我正在制作一个代码,该代码应该接收一个 csv 文件并从每一列返回两个列表。如果输入的文件不是 csv 文件或文件不存在,我需要创建一个返回错误的异常

import csv

def read_data(input_file_name):
    """ (str) -> list, list

    Read data from the path specified by the string input_file.
    Data looks like:

    18,  120
    20,  110
    22,  120
    25,  135

    Output two lists, one for each column of data.
    """
    try:
        l1 = []
        l2 = []
        with open(input_file_name, 'r') as f:
            csvin = csv.reader(f)
            for column in csvin:
                l1a = float(column[0])
                l1.append(l1a)
                l2a = float(column[1])
                l2.append(l2a)
        return l1, l2
    except:
        

这就是我目前拥有的

【问题讨论】:

    标签: python


    【解决方案1】:

    看看Python documentation。 在您当前的情况下,请考虑OSErrorFileNotFoundError 或用户定义的异常。

    try:
       ... # your code here
    except Exception: # change "Exception" to OSError or FileNotFoundError
       ... # code if error happened
    

    顺便说一句,我找到了你的similar question

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多