Whats the time? Time to get ill!

So lets make a python script that creates a folder on your desktop named ‘todays date’. Why you ask? Why not I say? In all seriousness this example will demonstrate some of the basic python concepts. Also I use stuff like this all the time. In fact, today, I figured out a way to spit out a .csv file from a database and compare it to another .csv. Nerd Alert! But it really helps in scheduling. Anyway I digress …

Go get python from here if you don’t already have it installed.

Here is the code, note I am writting this on a mac, so if your on windows the ‘myPath’ will look like this ‘C:\Documents and Settings\yourusername\Desktop’.

import os
from time import strftime
todaysDate = strftime('%Y_%m_%d')
myPath = '/Users/Chad/Desktop/'
myPath = myPath + todaysDate
print todaysDate
os.mkdir(myPath)

We’re going to store the path to your desktop in a variable. A variable is simply a place for you to store information. That info can be numbers or text. There are several types of variables, one of the most simple is a string. Thats what we will be dealing with in this example. A simple string of text that notes the location of your desktop in a variable.

So lets start back at the top. the import os is a call to a module. Python is efficient, it allows you to load only what you need. Each module has various commands and flags. Note the last line of the script os.mkdir(myPath) is in the form module.command(flag). It is the magic that actually makes the directory. Note that you can be very specific about the functions within modules, hence the from time import strftime.

strftime allows you to call the system time and format it in a lot of ways. Experiment and check the docs if you want to change the date format.

One last quick note. This line looks a little confusing huh? myPath = myPath + todaysDate.  All that is doing is concatenating variables. Concatenation is basically just mashing things together. So you are telling python that myPath is equal to whatever myPath already is plus the todaysDate variable.

Please note I have no formal programming training, and I am learning as I go.  The very fact that I am writing this is to share what I am learning, as I am learning it.  Corrections, comments, better practices are most welcome.


About this entry