Python 我们如何从两个不同的文件夹中读取相应的图像?

Python 我们如何从两个不同的文件夹中读取相应的图像?,python,Python,基本上,我的目录结构是: /第1条: --图像1.png --图像2.png . . . /第2条: --图像1.png --图像2.png . . . 我要做的是从Dir1和Dir2中读取相应的图像,如image1.png或image2.png,然后执行一些操作,如xor或其他任何操作。我的问题是单for循环,我发现很难遍历。 我正在尝试的是: from os import listdir d1 = 'Dir1' d2 = 'Dir2' d3 = 'Dir3'

基本上,我的目录结构是: /第1条: --图像1.png --图像2.png . . . /第2条: --图像1.png --图像2.png . . . 我要做的是从Dir1和Dir2中读取相应的图像,如image1.png或image2.png,然后执行一些操作,如xor或其他任何操作。我的问题是单for循环,我发现很难遍历。 我正在尝试的是:

    from os import listdir
    d1 = 'Dir1'
    d2 = 'Dir2'
    d3 = 'Dir3'
    f1 = [f for f in listdir(d1) if isfile(join(d1,f))]
    f2 = [f for f in listdir(d2) if isfile(join(d2,f))]
    for ( what to put here ?? ) in (what to put here?? ):
        img1 = # read image from d1
        img2 = # read image from d2
        # perform some operation
        #save to d3 
。。。如果您确信
f1
f2
的对应元素顺序相同,则可能会有所帮助,但
listdir
不能保证这一点。也许你最好对一个目录中的文件名做一个简单的
循环,如果它们存在的话,从两个目录中读取相同的文件名

顺便说一下,如果目录的内容可能不同,您可以通过以下方式轻松获得它们的通用文件名:

f1 = {f for f in listdir(d1) if isfile(join(d1,f))}
f2 = {f for f in listdir(d2) if isfile(join(d2,f))}
f_common = list(f1 & f2)

这回答了你的问题吗?你要找的是
zip
方法吗?它将允许您同时迭代两个列表
f1 = {f for f in listdir(d1) if isfile(join(d1,f))}
f2 = {f for f in listdir(d2) if isfile(join(d2,f))}
f_common = list(f1 & f2)