Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python以成对方式比较文件_Python - Fatal编程技术网

使用Python以成对方式比较文件

使用Python以成对方式比较文件,python,Python,我试图比较同一目录中两个文件的内容,以找到匹配的行。我希望最终以两两的方式来做这件事。现在,我已经编写了一些代码,这些代码将保持目录中的第一个文件处于打开状态,并将其与该目录中的其余文件进行比较。我在实现时遇到的问题是,对目录中的第二个文件重复该逻辑,然后是第三个文件,以此类推 我是Python新手,我只是利用到目前为止学到的知识来执行这段代码。我正在考虑为第一个文件添加另一个计数器。这样,一旦将文件与第一个文件进行了比较,file1counter就会向其中添加一个,因此现在file1read正

我试图比较同一目录中两个文件的内容,以找到匹配的行。我希望最终以两两的方式来做这件事。现在,我已经编写了一些代码,这些代码将保持目录中的第一个文件处于打开状态,并将其与该目录中的其余文件进行比较。我在实现时遇到的问题是,对目录中的第二个文件重复该逻辑,然后是第三个文件,以此类推

我是Python新手,我只是利用到目前为止学到的知识来执行这段代码。我正在考虑为第一个文件添加另一个计数器。这样,一旦将文件与第一个文件进行了比较,file1counter就会向其中添加一个,因此现在file1read正在打开file1read[1]并重复

import os
#define path where files to be compared are located
path = ("/path/to/files/")
#lists all files in a directory and sorts them alphabetically
files = sorted(os.listdir( path ))
#count the number of files in the directory
number_files = len(files)

count = 1
#open first file in the directory
file1 = open(path+files[0], 'r')
#store lines of the file 
file1read = file1.read().splitlines() 

#while loop to compare file 1 to file 2, then file 1 to file 3 ... to file n
while (count < number_files):
    file2 = open(path+files[count], 'r')
    file2read = file2.read().splitlines() 
    for i in file1read:
        for j in file2read:
            if i == j:
                print (os.path.basename(file1.name)+"_"+os.path.basename(file2.name)+" have {} in common".format(j))
    count = count + 1
导入操作系统
#定义要比较的文件所在的路径
路径=(“/path/to/files/”)
#列出目录中的所有文件并按字母顺序排序
文件=已排序(os.listdir(路径))
#计算目录中的文件数
文件数量=len(文件)
计数=1
#打开目录中的第一个文件
file1=打开(路径+文件[0],'r')
#存储文件的行
file1read=file1.read().splitlines()
#同时循环比较文件1和文件2,然后比较文件1和文件3。。。归档
而(计数<文件数):
file2=打开(路径+文件[count],'r')
file2read=file2.read().splitlines()
对于文件1中的我,请阅读:
对于file2read中的j:
如果i==j:
打印(os.path.basename(file1.name)+“”+os.path.basename(file2.name)+“have{}in common.format(j))
计数=计数+1
您可以使用它来获取目录中所有唯一的文件对和一组文件,以确定解决方案中文件之间的相似性。此外,该软件包的功能比os.listdir更好,因为它列出了给定目录中文件的正确路径:

import itertools
import glob

path = ("/path/to/files/")

for files in itertools.combinations(glob.glob(path + '*'), 2):
    file1, file2 = map(open, files)
    similarities = set(file1).intersection(file2)
    if similarities:
        print('_'.join(files), 'have {} in common'.format(','.join(similarities))

这可能很有用。试试看,你想知道这对被认为是完全匹配的文件,还是只有部分匹配?部分匹配。每个文件都是一个列表,我希望输出列表之间共享的任何项目。