有两个文本文件a.txt、b.txt,格式如下:
a.txt:
1 abc
2 cde
3 bf5
5 dnf
b.txt:
5 dnf
1 poi
2 teg
4 afp
以上两个文件分隔符均为tab,请用python写一个脚本,将以上两个文件内容的差异写到一个文件中,并按照第一列的数字升序排列.
# coding:utf-8 # @Time : 2018/5/4 14:43 # @Author : vglede # @File : compare_file.py # @Software: PyCharm Community Edition import os import sys BASE_DIR=os.path.abspath('.') sys.path.append(os.path.join(BASE_DIR,"conf")) sys.path.append("F:\pyscript\py2\conf\") #print sys.argv a_file_path="F:\pyscript\py2\conf\a.txt" b_file_path="F:\pyscript\py2\conf\b.txt" c_file_path="F:\pyscript\py2\conf\c.txt" class Operator_File: def read_file(self,Filename): self.file = Filename with open(self.file,'r') as f: #去除读取文件的 return ''.join(f.readlines()).strip(' ').split(' ') def write_file(self,Filename,contents,type_flag): self.file = Filename with open(self.file,type_flag) as f: if isinstance(contents,list) or isinstance(contents,tuple):for f_lines in contents: f.write('%s '%f_lines) elif isinstance(contents,str): f.write(contents) elif isinstance(contents,dict): for item in contents.items(): f.write(item) class FileCompare: def compare_file_diff(self,src_list1,src_list2): dest_list=[] for line in src_list1: if line not in src_list2: dest_list.append(line) return dest_list
#get the object of the class of=Operator_File() a_list=of.read_file(a_file_path) b_list=of.read_file(b_file_path) #print a_list #print b_list cmf=FileCompare() dest_list=cmf.compare_file_diff(a_list,b_list)+cmf.compare_file_diff(b_list,a_list) #print dest_list #print type(dest_list) #sort默认不写(reverse=False)按照升序排列 # ,需要降序的话reverse=True排序即可 dest_list.sort(reverse=False) #print dest_list of.write_file(c_file_path,dest_list,'w+')