csv 与语法有关的代码错误将填充添加到字符串的右侧

eh57zj3b  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(104)

有人能帮我解决这个valueError:

def movie_fetch_data(movie_csv):
    with open(movie_csv, "r") as movie_file:
        reader = csv.reader(movie_file)
        movie_info = []
        for row in reader:
            movie_info.append(row)
        return movie_info    

''' The data has been printed as a linked list'''

def movie_print_data(data):
    for title, genre, rotten, grass, year in data:
        print("{:36} {:10} {:18} ${:16} {}".format(title, genre, rotten, grass, year))

movie_data = movie_fetch_data(movie_csv) 
movie_print_data(movie_data)
Traceback (most recent call last)
Input In [23], in <cell line: 2>()
      1 movie_data = movie_fetch_data(movie_csv) 
----> 2 movie_print_data(movie_data)`your text`

Input In [22], in movie_print_data(data)
      1 def movie_print_data(data):
----> 2     for title, genre, rotten, grass, year in data:
      3         print("{:36} {:10} {:18} ${:16} {}".format(title, genre, rotten, grass, year))

ValueError: too many values to unpack (expected 5)

我尝试创建接受参数数据的函数movie_print_data,我想使用解包方法来引用列表中的每个元素。

wgx48brx

wgx48brx1#

正如其中一条评论中提到的,您遇到的问题是由底层CSV缺少数据引起的。当您无法保证序列中的元素数量时,元组解包不是一种合适的方法:
1.您无法确定缺少哪个元素
1.因此错误处理变得非常具有挑战性。

快速修复方法是在读入数据时用空字符串填充缺失的数据。这样,阅读数据后执行的任何步骤都可以确保任何下游步骤都可以依赖该数据:

EXPECTED_VALUES_PER_ROW = 5

def row_has_all_values(row: list) -> bool:
return EXPECTED_VALUES_PER_ROW == len(row)

def get_num_missing_values(row: list) -> int:
return EXPECTED_VALUES_PER_ROW - len(row)

def pad_row_with_empty_stings(row: list, missing_values: int) -> list:
null_padding = [""] * missing_values
return [*row, *null_padding]

def movie_fetch_data(movie_csv):

with open(movie_csv, "r") as movie_file:
    reader = csv.reader(movie_file)
    movie_info = []

    for row in reader:
        
        if not row_has_all_values(row):
            num_missing_values = get_num_missing_values(row)
            row = pad_row_with_empty_stings(row, num_missing_values)
        movie_info.append(row)

    return movie_info   

相关问题