文件操作综合练习:已知有两个文本文件内容为地址本,如下图:
在address1.txt中的内容为姓名和电话号码,在address2.txt中的内容为姓名和邮箱地址,要求合并两个地址本,合并后效果如下:
?
代码:
# 定义三个字典,放数据
address1 = {}
address2 = {}
new_address = {}
# 定义个函数,用来存数据进字典
def func(address, f):
ls = []
for line in f.readlines():
ls.append(line.strip().split(",")) # strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
for i in ls:
address[i[0]] = i[1]
# 打开文件,调用函数存数据
with open("address1.txt", 'r+') as f1:
func(address1, f1)
with open("address2.txt", 'r+') as f2:
func(address2, f2)
# 判断合并
# 先新建一个文件,放合并后的内容
with open("new_address.txt", 'w+') as f3:
ls = []
top = "姓名\t\t\t电话\t\t\t邮箱"
ls.append(top + "\n")
# 判断
for key in address1.keys(): # 取出address1的所有键
if key in address2.keys(): # 如果键也在address2的所有键里
s = key + "\t\t" + address1[key] + "\t\t" + address2[key] # 执行操作
else: # 否则,如果键不在address2的键中,则邮箱显示为****
s = key + "\t\t" + address1[key] + "\t\t" + "**********"
ls.append(s + "\n")
for key_i in address2.keys(): # 取出address2的所有键
if key_i not in address1.keys(): # 如果键不在address1的所有键里
s = key_i + "\t\t" + "**********" + "\t\t" + address2[key_i] # 则让电话号码显示为***
ls.append(s + "\n")
f3.writelines(ls)
f3.seek(0)
for line in f3:
print(line, end='')
?
|