+from os import mkdir, remove
+from os.path import exists, basename, dirname
+from datetime import datetime
+ """ Make a single directory if it does not exist. """
+ if not exists(dirname):
+def make_dirs_if_needed(dirnames = ):
+ """ Ensure a set of directories exists, making any that do not. """
+ for dirname in dirnames:
+def backup_existing_file(filename, backup_prefix = ''):
+ Backup an existing file with an optional custom prefix and timestamp. The
+ backup copy is bzipped for space savings.
+ time_list = list(datetime.now().timetuple())
+ time_list = time_list[0:6]
+ timestamp = "".join([str(x) for x in time_list])
+ bzip_file(filename, "%s/%s%s.bak.%s" % \
+ (dirname(filename), backup_prefix, basename(filename), timestamp))
+def bzip_file(source, dest = None):
+ Shortcut to bzip a file. The second parameter is optional, and defaults to
+ the original name of the file if nothing is given. Regardless, the dest
+ also has the 'bz2' extension added automatically, so you don't need to pass
+ bz_file = BZ2File(dest, 'w')
+ in_file = open(source, 'rb')
+def close_and_open_file(filename, file_obj = None):
+ """ Closes an open file, then re-opens it immediately. """
+ return open(filename, "w")