Search code examples
pythonfor-loopenumeration

Show progress in for loop by counting the images already processed [Python]


I would like to count the amount of pictures already converted. Therefore I have to modify print('converting') somehow.

def convert(self):          
        directory = [fn for fn in os.listdir(self.destination_folder) 
                      if any(fn.endswith(ext) for ext in included_extensions)]
        for item in directory:
            if item.endswith('.jpg' ): 
                img = Image.open(self.destination_folder + item)
                pathx = self.destination_folder + item
                convert='mogrify -virtual-pixel Black +distort Plane2Cylinder 53 -crop 2060x2060+620+202 %s' %pathx
                
                subprocess.run(convert, env={'PATH': path_cur})
                print('converting')

The output should be something like. xxx should be the total amount of files in directory.

converting [1/xxx]
converting [2/xxx]
converting [3/xxx]
...

How can I get this output?


Solution

  • Without having access to your data, something perhaps like:

    def convert(self):          
            directory = [fn for fn in os.listdir(self.destination_folder) 
                          if any(fn.endswith(ext) for ext in included_extensions)]
    
            train_length = len(directory)
            counter = 1
    
            for item in directory:
                if item.endswith('.jpg' ): 
                    img = Image.open(self.destination_folder + item)
                    pathx = self.destination_folder + item
                    convert='mogrify -virtual-pixel Black +distort Plane2Cylinder 53 -crop 2060x2060+620+202 %s' %pathx
                    
                    subprocess.run(convert, env={'PATH': path_cur})
                    print('converting', '[',counter,'/', train_length, ']')
                    counter += 1
    

    The enumerate method in the comments above is better.