There are two text files a.txt, b.txt, the format is as follows:
a.txt:
1 abc
2 cde
3 bf5
5 dnf b.txt
:
5 dnf
1 poi
2 teg
4 afp The
above two file separators are tab, Please write a script in python to write the difference of the contents of the above two files into a file and sort them in ascending order according to the numbers in the first column.
# 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: #Remove the \n of the read file return '' .join(f.readlines()).strip( ' \n ' ).split( ' \n ' ) 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\n'%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 is not written by default (reverse=False) in ascending order # , if you need to sort in descending order reverse=True Just dest_list.sort (reverse= False) # print dest_list of.write_file(c_file_path,dest_list, ' w+ ' )