how to compare lines in two files are same or different in python

后端 未结 3 711
攒了一身酷
攒了一身酷 2020-12-22 04:44

I have two files which contains following lines:

file1:
6.959999999:    LOG_MOD_L0_RECEIVE_TXBRP_CONTROL(0, 
 0x0059005f, 
 0x0049006d, 
 0x00b9008b, 
 0x001         


        
3条回答
  •  时光说笑
    2020-12-22 05:33

    You'll first need to solve the problem of locating the right, matching section. The following generator function will produce the section information you are looking for:

    def find_sections(filename, text):
        with open(filename) as fin:
            section = None
            for line in fin:
                if text in line:
                    section = line.rpartition('(')[-2:]
                    try:
                        while ')' not in line:
                            line = next(fin)
                            section.append(line)
                    except StopIteration:
                        pass  # ran out of file to read
                    yield ''.join(section)
                else:
                    previous = line
    

    To test if the same data exists in both files, read one first and collect all data in a set:

    output1_string=raw_input("Enter the String of file1:")
    sections1 = set(find_sections("C:\\Python27\\output1.txt", output1_string))
    

    Now you can find matching entries in the other file by doing a set intersection:

    output2_string=raw_input("Enter the String of file2:")
    sections2 = find_sections("C:\\Python27\\output2.txt", output1_string)
    for match in sections1.intersection(sections2):
        print 'Found a match:'
        print match
    

提交回复
热议问题