Archive for April, 2007

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”)))