Python loop in the directory inside directory
Question: I currently have the python code which loops in the directory, if it finds
another directory inside the directory, then it goes inside it & loops it
again to get all the files inside it. The directory traverse only one level.
Here is the code :

    
    
    import io
    import sys, os
    import glob
    reload(sys)
    sys.setdefaultencoding("utf-8")
    
    directory = u"F:\\songs"
    
    
    count=0;
    songs = glob.glob(os.path.join(directory, u"*"))
    with io.open('filenames.txt', encoding='utf-8') as newnames:
        for filename in newnames:
            try:
                print directory + "\\" + songs[count]
                if "####" in filename:
                    innersongs = glob.glob(os.path.join(directory, songs[count]))
                    for innerfilename in innersongs:
                        print directory + "\\" + songs[count] + "\\" + innerfilename
                        os.rename(oldpath, newpath)
                else:
                    print "hhy"
                    os.rename(oldpath, newpath)
                count += 1
            except IOError as (errno, strerror):
                print "I/O error({0}): {1}".format(errno, strerror)
            except:
                print "Unexpected error:", sys.exc_info()[0]
                raise
    

Above is the code which does the following i mentioned. Below is the names of
the file with which it gets renamed. Filename is filenames.txt

    
    
    abcd sdfdd dfdcbv
    ####amcdn dfghfgn yrtyrt
    @@@@abcdk eruifgf oirer
    @@@@eprouri kdfjdkfd soieeure dlfkdl
    @@@@weoerto oeruoture oitretre
    @@@@ewpoire gkjdfkg sdfdsfl sdfsdhjfd
    tieruoigd s,dfkdsjf dsfjbdjsf
    dfrkewire dgngfkdgdf fdgkjdfg
    gmfdghjfdhgdfg
    dfgfdgdf skdfhds sdfhsdjhf sdfitertre
    weikds dgkjksdf asouew sdfhds sdfj
    

Above is the sample file. In the current scenerio, whenever it gets the `####`
in the file, then the script gets to know that it is the name of the
directory, so go inside it & all `@@@@` are the name of the sudirectories or
files in the inner directory. After `@@@@` is over, we gets out of the inner
directory loop & loop over the current directory for changing the file names.

But i stuck at the inner loop to move inside & change the name of inner
directory file. What wrong i am doing here ? What else i can improve in the
code ?


Answer: Such a weird format. I don't really understand what it's for, so doing a wild
guess – I recommend using json, e.g.
[tree.json](http://pastebin.com/RHBRRFxc).

To use this in Python:

## tree.py

    
    
    import json
    
    def process_tree(prefix, element):
        for key, val in zip(element.keys(), element.values()):
            if type(val) is dict:
                process_tree(key, val)
            elif type(val) is list:
                if val:
                    print('Renaming {0}/{1} to {0}/{2}'.format(prefix, val[0], val[1]))
    
    if __name__=='__main__':
        tree = json.load(open('tree.json'))
        process_tree('.', tree)
    

In this example, `json.load` converts a json into `dict` with nested `dict`s
and `list`s, so you can iterate over them. Also, this example is based on
recursion – process_tree calls itself to process a child `dict` while
processing a parent `dict`.

Its output:

    
    
    Renaming ./sdfdd to ./dfdcbv
    Renaming ./skdfhds to ./sdfhsdjhf
    Renaming amcdn/gkjdfkg to amcdn/sdfdsfl
    Renaming amcdn/eruifgf to amcdn/oirer
    Renaming amcdn/dfghfgn to amcdn/yrtyrt
    Renaming amcdn/oeruoture to amcdn/oitretre
    Renaming amcdn/kdfjdkfd to amcdn/soieeure
    Renaming ./dgkjksdf to ./asouew
    Renaming ./s,dfkdsjf to ./dsfjbdjsf
    Renaming ./dgngfkdgdf to ./fdgkjdfg
    

Again, I don't really understand what your code was meant to do, so my code
has obvious limitations. Elements with empty values (e.g. empty list) are
ignored (`if val:` checks if value is empty). If element value (`val`) is not
a `dict`, element name (`key`) is not used at all (otherwise, it becomes a
prefix). If `list` has more than two elements, only first two are used.

Anyway, you know better how to rewrite this, if this _slightly_ fits your
needs. :)

