Python 代码仅从 csv 文件读取 1 个值 [已关闭]

问题描述 投票:0回答:1

Python 文件:

names = []

with open("names.csv") as file:
    for line in file:
        name, colour = line.rstrip().split(",")
        print(f"{name}, {colour}")

CSV 文件:

John,Green
Amy,Blue
Adam,Red
Oliver,Orange

当 CSV 文件中有 2 个值时,为什么会返回

ValueError: not enough values to unpack (expected 2, got 1)

python
1个回答
0
投票

要解决该问题,您应该在代码中添加一些错误处理。这是代码的更新版本,其中包括错误处理,以处理行不包含预期值数量的情况:

names = []

with open("names.csv") as file:
    for line in file:
        # Split the line into name and colour
        values = line.rstrip().split(",")

    # Check if there are enough values in the line
    if len(values) == 2:
        name, colour = values
        print(f"{name}, {colour}")
    else:
        print(f"Skipping invalid line: {line}")

此修改后的代码检查通过分割行获得的值的数量是否等于 2。如果不等于,它会打印一条消息,指示该行被跳过。这样,您就可以识别并处理 CSV 文件中不符合预期格式的行。

© www.soinside.com 2019 - 2024. All rights reserved.