将电话簿TeleAddressBook.txt和电子邮件EmailAddressBook.txt合并为一个完整的AddressBook.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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实现文件信息进行合并实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://blog.csdn.net/m0_38066258/article/details/77101495