CSV文件函数如果为空,则应返回无,如果未找到文件,则应返回错误

ego6inou  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(129)

我的代码应该读取一个csv文件,并返回字典列表的信息。然而,它不起作用。

import csv
def read_csv(fname):
    stu_list = []
    try:
        with open(fname, 'r') as students:
            reader = (csv.reader(students))
            for row in reader:
                avg = sum(float(grade) for grade in row[2:]) / 10
                rounded_avg = round(avg, 3)
                student_info = {'name': row[0], 'section':row[1], 'scores':[grade for grade in row[2:]], 'average':rounded_avg}
                stu_list.append(student_info)
            if len(stu_list) == 0:
                return None
            print(stu_list)
    except:
        print(f"Error occurred when opening {fname} to read")
        return None

字符串

mzmfm0qo

mzmfm0qo1#

基本上你需要做的就是返回stu_list

print(stu_list)

字符串

return stu_list


然后把指纹放在通话地点

print(read_csv('students.csv'))


我个人认为return None的东西有点不像Python,因为它中断了快乐路径的流动(在那里没有错误)。我会允许异常传播给用户,让他们决定如何处理它们。
一些更新的代码

import csv

def read_csv(fname):
    stu_list = []
    with open(fname, 'r') as students:
        for row in csv.reader(students):
            name, section, *scores = row
            avg = sum(float(grade) for grade in scores) / len(scores)
            student_info = {'name': name, 'section': section, 'scores': scores, 'average': round(avg, 3)}
            stu_list.append(student_info)
        return stu_list

if __name__ =='__main__':
    from sys import argv, exit

    if len(argv) < 2:
        print('must provide file name')
        exit(1)

    filename = argv[1]
    try:
        values = read_csv(filename)
        if values:
            print(values)
        else:
            print(f"Error student list {filename} is empty")
    except:
        print(f"Error occurred when opening {filename} to read")

y3bcpkx1

y3bcpkx12#

几点观察:
1.当学生列表不为空时,我没有看到任何返回它的语句。这就是为什么你得到None。为了解决这个问题,在你print(stu_list)的地方,返回stu_list
1.不要使用裸except,也就是没有任何特定错误的except。这种做法是危险的,因为它会隐藏严重的错误,使调试非常困难。在这种情况下,我建议使用FileNotFoundError。更好的是,我根本不会使用try/except,让调用者处理错误。
1.在计算平均值时,我使用statistics.mean而不是硬编码10作为等级数。
代码:

import csv
import statistics

def read_csv(fname):
    stu_list = []
    try:
        with open(fname, "r") as students:
            reader = csv.reader(students)
            for row in reader:
                scores = [float(grade) for grade in row[2:]]
                avg = statistics.mean(scores)
                rounded_avg = round(avg, 3)
                student_info = {
                    "name": row[0],
                    "section": row[1],
                    "scores": scores,
                    "average": rounded_avg,
                }
                stu_list.append(student_info)
            if len(stu_list) == 0:
                return None
            return stu_list
    except FileNotFoundError:
        print(f"Error occurred when opening {fname} to read")
        return None

字符串

相关问题