Archive for the ‘Python’ Category

Listing Files with Python

Thursday, April 26th, 2007

Getting a list of files in a directory and its sub directories is very simple using the built in os module in Python. In this example the file can be run with the directory to explore as the command line argument. Any directories found in the given directory will be recursed on and their files added the final list of all files.

# Emgarten.com April 26th, 2007
import os,sys

def findFiles(dir):
  files = []

  # remove a trailing slash if it exists
  if dir[-1:] == "/":
    dir = dir[0:-1]

  # loop through files and directories
  for x in os.listdir(dir):
    if os.path.isdir(dir + "/" + x):
      # list this dir also
      files.extend(findFiles(dir + "/" + x))
    else:
      # add the file to the list
      files.append(dir + "/" + x)
  return files

if __name__ == "__main__":
  if len(sys.argv) != 2:
    print "Usage: %s <dir>" % sys.argv[0]
    sys.exit(1)

  # get the list of files
  files = findFiles(sys.argv[1])

  for file in files:
    print file

The function returns a list with the full path of all files found in the directory.

MySQL Datetime string to a Timestamp

Monday, April 16th, 2007

Here is a simple function to convert a datetime string from MySQL to a UNIX timestamp using Python.

import time
# Converts an SQL datetime to a UNIX timestamp
# Example datetime: 2007-04-15 08:29:39
def sqlDateTimeToTimeStamp(sqlDateTime):
return int(time.mktime(time.strptime\
(sqlDateTime,\
“%Y-%m-%d %H:%M:%S”)))

Power of the Python FOR loop

Friday, January 19th, 2007

The FOR loop in Python can do a few more tricks then it can in other languages, and works in slightly different ways in what it pulls out depending on what object type you are looping on.

Looping on a String

x = “text”
for c in x:

print c

The Result:

t
e
x
t

The for loop loops over each character in the string and puts it in the c variable.

Looping on a list or tuple

Looping on a list or tuple is pretty standard, but can be done in two ways. You can go by the index number or you can let Python handle it.

Classic For Loop

myList = ["a","b","c"]
for i in range(0,len(myList)):

print myList[i]

Foreach Style

myList = ["a","b","c"]
for item in myList:

print item

Both of these have the same result, and just print out each list element.

Looping on a dictionary

Looping on a dictionary is a little different since we have a key for each element. When it is looped on the key is what is given, and if you want to access the actual value you need to use the key in the dictionary to get it out.

myDict = {}
myDict["first"] = “a”
myDict["second"] = “b”
myDict["third"] = “c”
for key in myDict:

print myDict[key]