使用目录中所有可能的文件组合作为python的输入

使用目录中所有可能的文件组合作为python的输入,python,Python,我在python中有一个程序,它使用两个文件作为输入,并计算它们之间的相似性。我想使用目录中所有可能的文件组合作为输入。如何使用python扩展我已有的脚本来实现这一点 我知道有一些工具,比如glob,可以遍历整个文件。但是,如何创建所有不同的文件组合 此外,作为@hcwhsa和@Ashish Nitin Patil,itertools如何与glob相结合 谢谢你的见解 进一步详情: 我的代码需要两个相同的输入(我有大约50个这样的文件的目录)。 每个输入是三个选项卡分隔的列(值1、值2、重量)

我在
python
中有一个程序,它使用两个文件作为输入,并计算它们之间的相似性。我想使用目录中所有可能的文件组合作为输入。如何使用
python
扩展我已有的脚本来实现这一点

我知道有一些工具,比如
glob
,可以遍历整个文件。但是,如何创建所有不同的文件组合

此外,作为@hcwhsa和@Ashish Nitin Patil,
itertools
如何与
glob
相结合

谢谢你的见解

进一步详情:

我的代码需要两个相同的输入(我有大约50个这样的文件的目录)。 每个输入是三个选项卡分隔的列(值1、值2、重量)。 基本上,根据这些信息,我计算jaccard系数,如下所示:

我想为目录中所有可能的文件组合计算这个系数。 到目前为止,我在本地将每个文件称为:

with open('input_file1', 'r') as infile_B:
with open('input_file2', 'r') as infile_B:
我的目标是在目录中所有可能的文件组合上迭代函数

import itertools
import os
for file_1, file_2 in itertools.combinations(os.listdir(os.getcwd()), 2):
    print(file_1, file_2)
    # compare the files

用目录路径替换
os.getcwd()

此代码段比较
路径中的所有文件

import os
from itertools import combinations

path = r'path/to/dir'
entries = os.listdir(path)
filenames = [os.path.join(path, entry) for entry in entries if os.path.isfile(os.path.join(path, entry))]

for (file1, file2) in combinations(filenames, 2):
    with open(file1) as f1, open(file2) as f2:
        # Compare the files
在Python3中,它可以做得更优雅一些

import os
from itertools import combinations

path = r'path/to/dir'
root, _, rel_filenames = next(os.walk(path))
full_filenames = [os.path.join(root, f) for f in rel_filenames]

for (file1, file2) in combinations(full_filenames, 2):
    with open(file1) as f1, open(file2) as f2:
        # Compare the files

这正是我答案中的代码所给出的——给定文件夹中所有文件的所有文件名组合。我遗漏了什么吗?不,这正是我所需要的-那么使用它也应该使用每个文件组合作为各种输入?这就是我不确定我是否也需要类似于
glob
的东西的地方。使用您的解决方案,程序将创建并直接使用
input1
input2
的所有可能组合?这是主要的问题-如果我没有清楚地表达我自己,我很抱歉。你能提供一个样本输入和预期输出的列表吗?我仍然认为我的答案回答了你问题的第一部分——它输出文件夹中所有可能的文件组合。如果我理解正确,它是一个可以为您筛选特定文件的工具,而不是一个迭代文件的工具。如果您只需要具有特定扩展名的文件,可以将文件名行更改为以下内容:
filenames=[os.path.join(path,entry)for entry in entry If os.path.isfile(os.path.join(path,entry))和entry.split('.')[-1]=='py']
使用它将创建所有可能的input1和input2组合?这也将输出与subdirs的组合。这很好-我仍然不太清楚如何将其与
glob
链接。我还没有使用glob,所以我不知道这一点。你具体想做什么?如果您向我们提供一些您已有的代码,可能会有所帮助。
import os
from itertools import combinations

path = r'path/to/dir'
root, _, rel_filenames = next(os.walk(path))
full_filenames = [os.path.join(root, f) for f in rel_filenames]

for (file1, file2) in combinations(full_filenames, 2):
    with open(file1) as f1, open(file2) as f2:
        # Compare the files