Search code examples
pythonloopsfile-organization

Python: How to loop a process


I'm working on making a small app/script for putting my mp3's in a folder hierarchy the way I want it, as I haven't found a solution for Unix that is just quite right. So I decided to work on my own. This is an excerpt

if musfile[0]:
    m = musfile[0]
    tag.link(m)
    mar = str(tag.getArtist())
    mal = str(tag.getAlbum())
    mti = str(tag.getTitle())
    #m1track = str(tag.getTrack())
    os.rename(m,mar + ' - ' + mti + '.mp3')
    m = mar + ' - ' + mti + '.mp3'
    os.makedirs(newmusicdir + '/' + mar + '/' + mal + '/')
    shutil.copy(m,newmusicdir + '/' + mar + '/' + mal + '/')

if musfile[1]:
    m = musfile[1]
    tag.link(m)
    mar = str(tag.getArtist())
    mal = str(tag.getAlbum())
    mti = str(tag.getTitle())
    #m1track = str(tag.getTrack())
    os.rename(m,mar + ' - ' + mti + '.mp3')
    m = mar + ' - ' + mti + '.mp3'
    os.makedirs(newmusicdir + '/' + mar + '/' + mal + '/')
    shutil.copy(m,newmusicdir + '/' + mar + '/' + mal + '/')

And so on. However, in order to organize more than one file, I have been just reusing blocks of code. However, this is extremely inefficient for several blocks of code. For example, if I wanted to organize just 50 songs with my method, I would have over 500 lines of code, for something so simple. So I was wondering if there is anyway I could use loops. However, the problem with using loops is that with each block I must change the number in the list. For example, from block one to two, I must change musfile[0] to musfile[1], and I do not know how to do that with loops. In fact I have little knowledge about loops. Am I clear enough?


Solution

  • import os, os.path
    import shutil
    
    for m in musfile:
        tag.link(m)
        mar = str(tag.getArtist())
        mal = str(tag.getAlbum())
        mti = str(tag.getTitle())
        new_name = mar + ' - ' + mti + '.mp3'
        os.rename(m, new_name)
        new_dir = os.path.join(newmusicdir, mar, mal)    #use os.path.join instead of +'/' to be more multi platform, it is a good habit
        try:
            os.makedirs(new_dir)
        except:
            pass
        shutil.copy(new_name, new_dir)