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)
?
要解决该问题,您应该在代码中添加一些错误处理。这是代码的更新版本,其中包括错误处理,以处理行不包含预期值数量的情况:
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 文件中不符合预期格式的行。