Search code examples
pythonloopspathlib

How to loop through multiple paths using pathlib


Trying to list, for example, all the jpgs on two drives. Single drive search looks like:

from pathlib import Path

for path in Path("/Volumes/MasterOne").rglob('*'):
    for file_name in path.glob('*.jpg'):   
        print(file_name)

But am not finding how to add a second volume to the for loop and iterate for files on both drives.

paths = ("/Volumes/MasterOne", "/Volumes/MasterTwo")

Solution

  • You might add outer for to get desired behavior as follows

    from pathlib import Path
    
    for p in ("/Volumes/MasterOne", "/Volumes/MasterTwo"):
        for path in Path(p).rglob('*'):
            for file_name in path.glob('*.jpg'):   
                print(file_name)