Reputation: 497
The title may sound confusing so here is what I want...
I have the following code:
import os
dir_list = os.walk('aFolder').next()[1] #aFolder is the directory location
SizeOfList = len(dir_list)
NumbOfList = 0
while (NumbOfList < SizeOfList):
print dir_list [NumbOfList]
NumbOfList = NumbOfList + 1
This code gets all the folders (not including subfolders) in the folder called 'aFolder' and shows them to the user. However, I want to store these folder names as different variables. The problem I have here is, I don't know the number of folders in this directory so I can't set 1 variable to dir_list [0]
and another to dir_list [1]
etcetera.
I need this because I want to select and choose certain folders with an if
statement. If you have an alternative to doing this than mine, I will happily accept it.
My solution to this was using a while loop. However, I can't figure out how to change the variable name each time the while loop repeats. I have tried this, this and this. The third link was the closest, but I still can't figure out how to implement it.
Thank you in advance to anyone who helps.
Upvotes: 0
Views: 1338
Reputation: 25895
If you want to see if a string is a substring of a folder in your list:
for directory in dir_list:
#Do stuff for everyone
if "mysubstring" in directory:
dospecialstuff()
Upvotes: 1
Reputation: 726
You asked me to expand my comment. Here it is:
import os
d=dict()
dir_list = os.walk('/tmp').next()[1]
for idx in range(len(dir_list)):
d.update({dir_list[idx]: idx})
for k, v in d.items():
print "k=", k, "v=", v
d.update({k: v+1}) # to update the variable
print "new value of <%s>"%(k), d[k]
print
Upvotes: 1