本帖最后由 ly123 于 2020-6-9 11:13 编辑
最近刚开始学Python,跟着做实例的时候和讲课的代码一样但是还是报错,不知道怎么改进,还望大佬指点{:1_936:}
代码:
[Python] 纯文本查看 复制代码
def main():
f1=open('teleAddressBook.txt','rb')
f2=open('emailAddressBook.txt','rb')
f1.readline()
f2.readline()
lines1=f1.readlines()
lines2=f2.readlines()
dic1=[]
dic2=[]
for line in lines1:
elements = line.split()
dic1[elements[0]]=str(elements[1].decode('utf-8'))
for line in lines2:
elements = line.split()
dic2[elements[0]]=str(elements[1].decode('utf-8'))
lines=[]
lines.append('姓名\t 电话 \t 邮箱\n')
for key in dic1:
s=''
if key in dic2.keys():
s='\t'.join([str(key.decode('utf-8')),dic1[key],dic2[key]])
s+='\n'
else:
s='\t'.join([str(key.decode('utf-8')),dic1[key],str('----------')])
s+='\n'
lines.append(s)
for key in dic2:
s=''
if key not in dic1.keys():
s='\t'.join([str(key.decode('utf-8')),str('----------'),dic2[key]])
s+='\n'
lines.append(s)
f3=open('AddressBook1.txt','w')
f3.writelines(lines)
f3.close()
f2.close()
f1.close()
print('The AddressBooks are merged!')
if __name__ == '__main__':
main()
-------------------------------------------------------
报错: dic1[elements[0]]=str(elements[1].decode('utf-8'))
TypeError: list indices must be integers or slices, not bytes
我也查过网上的,说改成int也不行。{:1_924:} 小白不懂应该怎么改,先谢谢各位!
感谢各位,是我太粗心了。字典应该是{},误用了[]。:shutup: |