I basically want to map out folders and subfolders in a dictionary and i have this code ive written, but instead of adding each filename to the dictionary it overwrites it each time.

Any suggestions?

for fname in os.listdir(os.getcwd()):
    print fname
    x += 1
    maincat = {fname}

print "x = " + str(x)
print maincat
print len(maincat)

Recommended Answers

All 6 Replies

Why not simply os.listdir(os.getcwd())?

because i specify a directory erlier in the program.

this bit of code was enough to get my point across. :)

or i might have misunderstood you, would you like to elaborate?
plus the for fname bit allows me to check that its picking up the subfolders correctly.

my end goal is to take the strings and assign a button for each subfolder. but i want to do as much of the coding as possible myself asking for the minimum amount of help in order to learn.

Ive got this so far

maincat = {}
x= -1 #because dictionaries order from 0 onwards right?

for fname in os.listdir(os.getcwd()):
    print fname
    x += 1
    maincat[x] = fname
    num_of_sub = x + 1

print "number of subfolders in directories = " + str(num_of_sub)
print maincat
print len(maincat)

only problem now is i wanted the names of the subfolders to be the key, whereas they are assigned an automatic number key from 0 up, but this will do for now.

Feel free to make further suggestions or comment on my solution before i mark this thread as solved later today. Thanks.

I solved this problem by changing the line

maincat[x] = fname

to

maincat[fname] = x

That way the filenames are the key, and the numbers serve as a nice little place holder.

You are talking of subfolders but you are listing also files. Make the program first function before starting to optimize. Don't however do wrong choices in data structures. Those are difficult to correct later. Luck with the project!

this is the function, im going to make one set of buttons represent the sub folders, and when these are clicked the other set of buttons change to represent the sub folders within that one folder, im storing the names in a dictionary to use the strings for the buttons.

my program searches in folder x, and reads the names of the folders inside, for example x1, x2, x3, i want it to then open x1, and list the folders within x1, and store those, for example x11, x12, x13. id also like it to do the same for x2.

once i know how to make my program do that i can crack on and attempt the rest of the code.

I just cant work my head around how to do it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.