Python Forum

Full Version: nested for loops glob
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to use a for loop and a nested for loop
So what I have is:

for f in glob("/Users/Desktop/network5"):
         for x in glob(f/NET_00*):
              print x
         break
    break
This doesn't give me any output.

I realize if I use glob I probably can't use the "f" I defined earlier in the for loop. But how can I use the same path that is assigned to f to use in the nested for loop, x?

For the nested loop, x, I wanted it to loop through all the files in that directory.
Walking through the files in directory:

import glob
import os


for path in glob.glob("/path/to/dir/*"):
    if os.path.isfile(path):
        print(path)
You must put * to the end of the path to walk through the all files and sub-directories.

You can use the path to from the first loop - it is simple string. Here is the example of printing files from all path's sub-directories:

import glob
import os


for path in glob.glob("/path/to/dir/*"):
    if os.path.isdir(path):
        for sub_path in glob.glob(path + "/*"):
            if os.path.isfile(sub_path):
                print(sub_path)
Thank you so much. But I had one more question that's slightly more difficult to answer perhaps.
That is, what if I wanted the first for loop to cycle through network(5-10) and then beneath that, add a nested loop that loops within each folder to extract all the files?

import glob 
import os
for f in glob("/Users/Desktop/network*"):
         for x in glob(f/NET_00*):
              print x
         break
    break
So basically if we are looking through folder, "network6", I want it to loop through all files and once its done looping through all files within network6 to then go on to network7 and loop through all the files in network 7, and so on and so forth.

NOTE: so the difference this time is that the first loop is also required to loop through the set of files
Well if you know the range of the networks, you can do it like this:

import glob
import os


# let's iterate between number 5 and 10
for network_number in range(5, 11):
    # converting network number to string with leading zero for number < 10
    network_number = str(network_number).zfill(2)
    # iterating files in particular network directory
    for path in glob.glob("/Users/Desktop/network/NET_" + network_number + "/*"):
        if os.path.isfile(path):
            print(path)