为何这段Python代码会报ValueError: too many values to unpack (expected 2)错误?
解决
ValueError: too many values to unpack (expected 2)及文件写入错误 你的代码存在两个关键问题导致报错,以下是具体修复方案:
1. 字典遍历方式错误
直接遍历字典conlst时,Python默认仅迭代字典的键,for key, value in conlst:这行代码尝试把单个键(字符串)拆成两个变量,必然触发too many values to unpack错误。
正确写法是使用字典的items()方法,它会返回字典的键值对元组:
for key, value in conlst.items():
2. 文件write方法参数错误
文件对象的write()方法仅接受一个字符串参数,传入key, value两个参数会触发参数数量错误。需要把键值对拼接成单个字符串再写入,比如添加分隔符和换行符:
lastf.write(f"{key}: {value}\n")
修改后的完整代码
import json # --1-- file = open("C:\\Users\\PycharmProjects\\p5.txt", 'w') for i in range(4): a = input("enter a sentence") file.write(a+"\n") file.close() file2 = open("C:\\Users\\PycharmProjects\\p5.txt", 'r') lines = file2.read().splitlines() last_line = lines[-1] print(last_line) # --2-- def splitname(): textf = open("C:\\Users\\PycharmProjects\\linuxEtcPassword.txt", 'r') ditailsd = {} for line in textf: newsplit = line.replace('\n', ' ').split(":") nv = {newsplit[0]: newsplit[2]} ditailsd.update(nv) dict1 = sorted(ditailsd.keys()) conlst = {dict1[d]: dict1[d + 1] for d in range(0, len(dict1)-1, 2)} print(conlst) lastf = open("C:\\Users\\PycharmProjects\\linuxEtcPassword1.txt", 'w') # 修复遍历和写入逻辑 for key, value in conlst.items(): lastf.write(f"{key}: {value}\n") lastf.close() # 手动关闭文件 file.close() splitname()
额外优化建议
推荐使用with语句管理文件,它会自动关闭文件,避免资源泄漏:
def splitname(): with open("C:\\Users\\PycharmProjects\\linuxEtcPassword.txt", 'r') as textf: ditailsd = {} for line in textf: newsplit = line.replace('\n', ' ').split(":") nv = {newsplit[0]: newsplit[2]} ditailsd.update(nv) dict1 = sorted(ditailsd.keys()) conlst = {dict1[d]: dict1[d + 1] for d in range(0, len(dict1)-1, 2)} print(conlst) with open("C:\\Users\\PycharmProjects\\linuxEtcPassword1.txt", 'w') as lastf: for key, value in conlst.items(): lastf.write(f"{key}: {value}\n")
内容的提问来源于stack exchange,提问作者user6631005
相关产品推荐
相关产品推荐

