Search code examples
pythonpython-3.xlistdir

TypeError: listdir() takes at most 1 argument (2 given)


I'm trying to iterate through 2 folders simultaneously since i want to work on pairs of images in two different location, unfortunately listdir takes only 1 argument so it doesn't allow me to iterate through both like in lists for example. Is there some other way to do this? Thank you

mypath2 = os.path.join('c:\\trainstcolor2')
images2 = list()


mypath = os.path.join('c:\\trainst2')
images = list()

for item,item2 in os.listdir(mypath,mypath2):

   image = cv2.imread(os.path.join(mypath, item))
   image2 = cv2.imread(os.path.join(mypath2, item2))

   if image is not None:

       images.append(image)
       images2.append(image2)

Solution

  • You do not want to use os.listdir as-is because (from the documentation):

    The [returned] list [of files] is in arbitrary order.

    Hence, you probably want the following:

    images1 = sorted(os.listdir(mypath))
    images2 = sorted(os.listdir(mypath2))
    
    for item, item2 in zip(images1, images2):
        # ...