Automated Unrarring

August 3, 2009 by humanumbrella Leave a reply »

So, I had a pack of National Geographic TV Episodes — but each one is packaged in little rar packs. In general I have to unrar the files, and remove the pieces. But since there was a folder of like 100 of these episodes I wrote a python script to do it for me! (:

It’s very rudimentary, and probably mostly inefficient –> for example, I didn’t know if there was ‘contains’ method so I just run through a for loop to find the right file. (:

This will remove everything but the avi file that remains once the unrarring is complete. a real time saver for me! (:

You will need this python module to use winrar: it’s by ‘chilkat’ –> http://www.example-code.com/python/rar_unrar.asp

Here it is:

import sys
import os
import chilkat

rar = chilkat.CkRar()
dirs = os.listdir('./')

for dir in dirs:
    if (dir.find("National") >=0):
        print dir+"\n\n"
        fileList = os.listdir(dir)
        for possibleMatch in fileList:
            if (possibleMatch.find(".rar") >= 0):
                rarFile = possibleMatch

        success = rar.Open(dir + "/" + rarFile)
        if (success != True):
            print rar.lastErrorText()
            sys.exit()
        else:
            print "opened"

        success = rar.Unrar(dir+"/")
        if (success != True):
            print rar.lastErrorText()
        else:
            print "Success."

        print "\n\n"+dir+"\n\n"

        path = "C:\\National.Geographic.Pack\\"+dir
        samplePath = path+"\\Sample\\"

        sampleAvi = os.listdir(samplePath)

        os.remove(samplePath+sampleAvi[0])
        os.rmdir(samplePath)
        for file in os.listdir(dir):
            if (file.find(".avi") < 0):
                if(os.path.isdir(file)):
                    os.rmdir(file)
                else:
                    try:
                        os.remove(path+"\\"+file)
                    except OSError:
                        print "OS Error"

            else:
                print "good"

I also wrote another one which would then take the period-explosion of names from downloads and rename it to something a little more human readable/nicer looking:

import sys
import os

dirs = os.listdir('./')

for dir in dirs:
    if (dir.find("National") >=0):
        asdf = dir.split('.')
        length = len(asdf)
        new = ''
        for x in asdf[2:length-2]:
            if (x.find("WS") < 0):
                new+=x+" "

        print new
        os.rename(dir,new)
Advertisement

Leave a Reply