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

2024-10-02 22:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我是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

Tags: 文件thetopathin目录numberos
1条回答
网友
1楼 · 发布于 2024-10-02 22:26:11

可以使用^{}获取目录中所有唯一的文件对,并使用一个集合来确定文件之间的相似性,就像在this解决方案中所做的那样。此外,^{}包的功能比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))

相关问题 更多 >