文件内容如下:
liuyang,123456
liyun,123456
zhangsna,12345lkj
#方法一:从文件中读取数据,一行读取一个列表,读取出一个嵌套的列表,再转换成字典
with open('users', 'r', encoding='utf-8')as f:
dic = []
for line in f.readlines():
line = line.strip('\n')
b = line.split(',')
dic.append(b)
dic = dict(dic)
print(dic)
#方法二:从文件中读取数据,一行读取一个列表,读取出一个嵌套的列表,再转换成字典
with open('users', 'r', encoding='utf-8')as f:
dic = []
for line in f.readlines():
line = line.strip('\n')
b = line.split(',')
dic.append(b)
new_dict = {}
for i in dic:
new_dict[i[0]] = i[1]
print(new_dict)
nums = new_dict.keys()[0]
print(nums)
print(nums[3])
#方法三:从文件中读取数据,一行读取一个列表,读取出一个嵌套的列表,再转换成字典
with open('users', 'r', encoding='utf-8')as f:
res = dict(line.strip().split(',') for line in f if line)
print(res)
执行过程中报错:dictionary update sequence element #8 has length 1; 2 is required
找了半天问题出现的原因,结果竟因为文件内的最后一行是空行导致的。好吧,我就不说什么了,建议查找问题的时候打印出每一步的操作结果,就发现问题了。