python如何合并两个文档内容
发布时间:2026-01-12 17:23:45

1、在合并两个文档之前


2、合并两个文件的代码:
file1=open("name,tel.txt","rb")
file2=open("name,email.txt","rb")
file_list1=file1.readlines()#将所有变量读入列表file_list1
file_list2=file2.readlines()#将所有变量读入列表file_list22
#print(type(file1)
#定义各属性数据存储列表
file_list1__________name=[]
file_list1__________tel=[]
file_list2_________list2______________name=[]
file_list2_________list2______________email=[]
#以下操作将在file_list1列表中获得的信息
formessageinfile_list1:
temp_list=message.split()
#使用split方法操作txt文件中的第一行,即file_list1列表中的第一项
将空格分成两部分,继续放在temp_list列表中
file_list1__________name.append(str(temp_list[0].decode('gbk')))#包括中文选择gbk
file_list1__________tel.append(str(temp_list[1].decode('gbk')))
#操作与file_list1列表完全相同
formessageinfile_list2:
temp_list=message.split()
file_list2_________list2______________name.append(str(temp_list[0].decode('gbk')))
file_list2_________list2______________email.append(str(temp_list[1].decode('gbk')))
#print(len(file_list1__________name))
#file_list1中的名称合并与file_list2中的名称相同...
file_list3=[]
foriinrange(len(file_list1__________name)):
s=''
iffile_list1__________name[i]infile_list2_________list2______________name:
j=file_list2_________list2______________name.index(file_list1__________name[i])#列表index方法查找括号中对象的返回值
s='\t'.join([file_list1__________name[i],file_list1____tel[i],file_list2___email[j]])
#字符串join方法连接三个属性,与(\t制表位)隔开
s+='\n'
else:
s='\t'.join([file_list1____name[i],file_list1____tel[i],str("--------------")])
s+='\n'
file_list3.append(s)
#选择file_list1中的名称与file_list2中的名称不同
foriinrange(len(file_list2_______name)):
s=''
iffile_list2_______name[i]notinfile_list1__name:
s='\t'.join([file_list2_______name[i],str('--------------'),file_list2___email[i]])
s+='\n'
file_list3.append(s)
#将数据写入file3
file3=open("三属性合并.txt","w")
file3.writelines(file_list3)
#关闭文件
file1.close()
file2.close()
file3.close()3、合并两份文件后的结果:

下一篇 python什么时候加self?
