ValueError:没有足够的值可解包.为什么? [英] ValueError : not enough values to unpack. why?

查看:288
本文介绍了ValueError:没有足够的值可解包.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个网站上学习文件管理,我尝试执行某个脚本,但对我来说效果不佳.

I am learning file management from a website and I tried executing a certain script but it hasn't worked out well for me.

它一直在以下行返回此错误:city, day, time = line.split()

It keeps returning this error at the line : city, day, time = line.split()

ValueError:没有足够的值可解包(预期至少为2,得到0)

ValueError: not enough values to unpack (expected at least 2, got 0)

我正在尝试按字母顺序排列并按腌制方式转储城市及其时区的列表,文本文件中包含以下几行:

I am trying to alphabetize and pickle dump a list of cities and their time zones, the text file has several lines such as this:

Salt lake city Sun 09:52
San Francisco Sun 00:52
Amsterdam Sun 08:52
Denver Sun 01:52
San Salvador Sun 01:52
Detroit Sun 02:52

这是代码:

import pickle

lines = open("cities_and_times.txt").readlines()
lines.sort()

cities = []
for line in lines:
    *city, day, time = line.split()
    hours, minutes = time.split(":")
    cities.append((" ".join(city), day, (int(hours), int(minutes)) ))

    f_new = open("cities_and_times.pkl", "bw")
    pickle.dump(cities, f_new)

    print(cities)

推荐答案

您需要一个if条件,该条件允许您跳过空白行.像这样:

You need an if condition which will allow you to skip over blank lines. Something like:

if not line:
   continue

# Or do this

if not line:
   pass
else:
   *city, day, time = line.split()

这篇关于ValueError:没有足够的值可解包.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆