Python实现文件信息进行合并实例代码
将电话簿TeleAddressBook.txt和电子邮件EmailAddressBook.txt合并为一个完整的AddressBook.txt
def main(): ftele1=open("d:\TeleAddressBook.txt","rb") ftele2=open("d:\EmailAddressBook.txt","rb") ftele1.readline() ftele2.readline() lines1=ftele1.readlines() lines2=ftele2.readlines() #建立空列表用于存储姓名电话Email list1_name=[] list1_tele=[] list2_name=[] list2_email=[] #获取TeleAddressBook for line in lines1: elements=line.split() list1_name.append(str(elements[0].decode("gbk"))) list1_tele.append(str(elements[1].decode("gbk"))) #获取EmailAddressBook for line in lines2: elements=line.split() list2_name.append(str(elements[0].decode("gbk"))) list2_email.append(str(elements[1].decode("gbk"))) lines=[] lines.append("姓名\t电话\t\t邮箱\n") #按索引方式遍历姓名列表 for i in range(len(list1_name)): s='' if list1_name[i] in list2_name: j=list2_name.index(list1_name[i]) s="\t".join([list1_name[i],list1_tele[i],list2_email[j]]) s+="\n" else: s="\t".join([list1_name[i],list1_tele[i],str("-----------")]) s+="\n" lines.append(s) for i in range(len(list2_name)): s="" if list2_name[i] not in list1_name: s="\t".join([list2_name[i],str("-----------"),list2_email[i]]) s+="\n" lines.append(s) #将新生成的合并数据写入新的文件中 ftele3=open("d:\AddressBook.txt","w") ftele3.writelines(lines) #关闭文件 ftele3.close() ftele1.close() ftele2.close() print("The addressBooks are merged!") main()
演示结果:
总结
以上就是本文关于Python实现文件信息进行合并实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16