问题如题所示,在python中怎样查看并比较两个文件的内容并返回相同的内容和下标,首先需要说明,我的文件是按行存储的,形式如下:

Python比较5个文件的数据的大小 python比较两个文件的内容_python


具体的代码如下:

import os

def read_file(filename1,filename2):
    path = "/home/zhuhualong/pycharm_proj/pycharm_proj/xbs_symptom_structure/result"
    filename1_path = os.path.join(path,filename1)
    filename2_path = os.path.join(path,filename2)
    same_result = []
    same_number = []
    idx1 = 1
    with open(filename1_path,'r+',encoding='utf-8') as file1,open(filename2_path,'r+',encoding='utf-8') as file2:
        f1 = file1.readlines()
        f2 = file2.readlines()
        for text1 in f1:
                idx2 = 1
                for text2 in f2:
                    if idx1 == idx2 and text1 == text2:
                        same_number.append(int(idx1))
                        same_result.append(text1)
                        idx2 += 1
                    else:
                        idx2 += 1
                idx1 += 1
        print(same_number)
        print(same_result)


read_file("xbs_struct_0724_3_2w_0","xbs_struct_0724_3_4w_0")

其中readfile()函数的参数是需要比较的文件名称,path是文件所在的文件夹路径,由于我这里的两个文件是在同一文件夹下,所以使用的是同一个path。