nested for loops glob - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: nested for loops glob (/thread-12965.html) |
nested for loops glob - devenuro - Sep-20-2018 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 breakThis 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. RE: nested for loops glob - ODIS - Sep-20-2018 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) RE: nested for loops glob - devenuro - Sep-20-2018 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 breakSo 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 RE: nested for loops glob - ODIS - Sep-20-2018 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) |