我正在从一个网站上学习文件管理,我尝试执行某个脚本,但对我来说效果不佳。
它一直在以下行返回此错误: city, day, time = line.split()
city, day, time = line.split()
ValueError:没有足够的值可解包(预期至少为2,得到0)
我正在尝试按字母顺序排列并按腌制方式转储城市及其时区的列表,该文本文件具有以下几行:
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条件,该条件允许您跳过空白行。就像是:
if not line: continue # Or do this if not line: pass else: *city, day, time = line.split()