A Python script a day keeps the doctor away

I’ve been teaching myself Python for a few months now, and have been doing it by reading a lot and following the exercises. I feel I have a decent handle on scripting with it, but have strange gaps based on portions that didn’t quite fit when I was reading things. In an attempt to fix this, I’ve decided that any file manipulations I do on my computer from now on will be done with Python, and I’ll play with some of the different options for doing them.

Today, I had a bunch of movie files that needed to be thrown into folders that are named with the movie file name, minus the extension. 10 minutes later, and I have a script that will move them for me, at need.

#!/usr/bin/python
#Written by Benjamin Kenneally
#05/29/11

import os

files = os.listdir((os.getcwd()))
for movie in files:
	fileExt = os.path.splitext(movie) [-1]
	if '.m4v' == fileExt:
		movieName = os.path.splitext(movie)[0]
		print "Handling %s." % (movieName)
		movieString = "%s/%s" % (movieName,movie)
		os.renames(movie, movieString)
		print "Moving %s to directory %s." % (movie,movieName)

	else:
		print "%s is not an .m4v file. Doing nothing." % (movie)

There’s probably a more efficient way to do the base directory handling, but I didn’t see it, and this works. I first tried to use

shutil.move

and

os.mkdir

to make directories and move the files, but it doesn’t like to play in the same filesystem you’re moving to, and I didn’t realize that. Now I know what it’s for, so that’s cool. Learn a little something every day, right?

So, not monumental, or anything, but I’ll post all the little scripts I throw up for everyday crap here, and talk about what I learned, if anything, in writing it. Plus, this can be a script library for me, then.

Comments on my crappy coding? Leave me some feedback!

Advertisements

~ by Benjamin Kenneally on May 29, 2011.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

 
%d bloggers like this: