如何防止ValueError:解压缩的值太多

时间:2018-02-05 16:21:16

标签: python

f =open(input("Enter the name of the password file: "),'r') #opens inputed file
lines = f.readlines()
list_=[]
credentials = {}
for line in lines:
        user, pw = line.strip().split(':') # error in this line
        credentials[user] = pw # creates a dict of usernames and passwords
        list_.append(pw) #creates a list of passwords
  

ValueError:解压缩的值太多(预期为2)。

文件格式应为user:password 如果文件中存在不一致,如何拆分用户名和密码以最终创建字典?我需要使用.items()吗?

1 个答案:

答案 0 :(得分:0)

用户名或密码中可能存在冒号':' - 更有可能在密码内。您可以在密码中忽略冒号及其后面的所有内容,将其截断。一种方法是使用

user, pw, *throwaway = line.strip().split(':')

如果该行符合预期,变量throwaway将为空列表。如果行中有额外的冒号,throwaway将是第二个冒号之后的项目列表,您可以忽略它。

我的解决方案的主要问题是,如果用户名中有冒号,该用户名的第一部分将被视为用户名,第二部分将被视为密码,以及任何其他部分用户名与密码一起被忽略。鉴于你声明的格式,我没有看到任何解决方法。另一个问题是,这可以防止在密码中使用冒号。