python编程:电话簿TeleAddressBook和邮箱地址簿EmailAddressBook两个文件,合并为一个完整的AddressBook文件

有电话簿TeleAddressBook和邮箱地址簿EmailAddressBook两个文件,使用字典结构将其合并为一个完整的AddressBook文件 。

python编程:电话簿TeleAddressBook和邮箱地址簿EmailAddressBook两个文件,合并为一个完整的AddressBook文件_第1张图片

变为:

python编程:电话簿TeleAddressBook和邮箱地址簿EmailAddressBook两个文件,合并为一个完整的AddressBook文件_第2张图片


代码如下:

# -*- coding:UTF-8 -*-

file1_read = open("file1", 'r')
file1_read.readline().decode("utf-8")
lines1 = file1_read.readlines()

file2_read = open("file2", 'r')
file2_read.readline()
lines2 = file2_read.readlines()

dict1 = {}
dict2 = {}

for line in lines1:
    element= line.split()
    # print s[0]
    dict1[element[0]] = element[1]
# print dict1

for line in lines2:
    element= line.split()
    # print s[0]
    dict2[element[0]] = element[1]
# print dict1
file1_read.close()
file2_read.close()

lines = []
s = "姓名\t电话\t\t\t邮箱\n"
lines.append(s)

for key in dict1.keys():
    if key in dict2.keys():
        s = "\t".join([key,dict1[key],dict2[key]])+'\n'
    else:
        s = "\t".join([key, dict1[key],'----------'])+'\n'
    lines.append(s)
# print lines

for key in dict2.keys():
    if key not in dict1.keys():
        s = "\t".join([key, '----------', dict2[key]])+'\n'
        lines.append(s)
# print lines
#
with open("file3",'w') as file3_write:
    file3_write.writelines(lines)
file3_write.close()








你可能感兴趣的:(python学习)