1、实现功能:合并2个文件内容,以3列内容显示,并整合内容。 1、文件mail内容: 李三,123@163.com 李二,133@163.com 李一,123@163.com 李四,123@162.com 李五,123@173.com 李六,223@163.com 李七,123@163.com 李八,125@163.com 李九,173@163.com 李十,186@163.com 刘三,188@163.com 申六,123@169.com 2、文件telephone内容: 李三,12234567789 李二,12234566789 王一,12334566789 李四,12234556789 张二,12234566889 张一,12234566799 张四,12734566789 李五,12744566789 刘六,12334566789 李七,12254566789 李八,12234766789 李九,12234568789 李十,12234566989
2、代码如下:
#!/usr/bin/python # -*- coding: UTF-8 -*- ad_tel={} #创建空字典,用于存储2个文件内容。 ad_mail={} def read_ad(): file1=open('telephone','r',encoding='UTF-8') lines1=file1.readlines() for line in lines1: line=line.strip() #去除首尾的多余空格,输出字符串类型数据如:“李四,12234556789” content=line.split(',') #按逗号来,分隔字符串 ad_tel[content[0]]=content[1] file1.close() file2=open('mail','r',encoding='UTF-8') line2=file2.readlines() for line in line2: line2=line.strip() content=line2.split(',') ad_mail[content[0]]=content[1] file2.close() def merge_ad(): address=[] #创建空列表来存放合并以后的数据。 header="姓名\t 电话\t\t 邮箱\n" #添加合并数据的头部标题 address.append(header) for key in ad_tel.keys(): line='' if key in ad_mail.keys(): #查找tel表中的key,同时也在mail表中的。 line=line+'\t'.join([key,ad_tel[key],ad_mail[key]]) #合并字符串,注意join后面是列表,\t是列表连接符号 line+='\n' #让显示换行 else: #查找tel表中的key,不在mail表中的。 line=line+'\t'.join([key,ad_tel[key],'***********']) #星号来填补空白 line+='\n' address.append(line) for key in ad_mail.keys(): line='' if key not in ad_tel.keys(): #查询mail中有,而tel表中没有的数据。 line=line+'\t'.join([key,'***********',ad_mail[key]]) line+='\n' address.append(line) with open('new_address','w',encoding='UTF8') as ad: #写入数据。 ad.writelines(address) if __name__=='__main__': read_ad() merge_ad()
3、输出内容如下:
姓名 电话 邮箱 李七 12254566789 123@163.com 刘六 12334566789 *********** 王一 12334566789 *********** 李二 12234566789 133@163.com 张四 12734566789 *********** 李四 12234556789 123@162.com 张一 12234566799 *********** 李五 12744566789 123@173.com 李三 12234567789 123@163.com 李八 12234766789 125@163.com 张二 12234566889 *********** 李九 12234568789 173@163.com 李十 12234566989 186@163.com 李一 *********** 123@163.com 李六 *********** 223@163.com 申六 *********** 123@169.com 刘三 *********** 188@163.com