Commits

Chad Burrus committed f733684

added FileUtils.py

Comments (0)

Files changed (1)

+from os import mkdir, remove
+from os.path import exists, basename, dirname
+from datetime import datetime
+from bz2 import BZ2File
+from glob import glob
+
+def make_dir_if_needed(dirname):
+	""" Make a single directory if it does not exist. """
+
+	if not exists(dirname):
+		mkdir(dirname)
+
+def make_dirs_if_needed(dirnames = []):
+	""" Ensure a set of directories exists, making any that do not. """
+
+	for dirname in dirnames:
+		make_dir_if_needed(dirname)
+
+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.
+	"""
+
+	if exists(filename):
+		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))
+		remove(filename)
+
+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
+		it in.
+	"""
+
+	if dest is None:
+		dest = source
+	dest = "%s.bz2" % dest
+	bz_file = BZ2File(dest, 'w')
+	in_file = open(source, 'rb')
+	for line in in_file:
+		bz_file.write(line)
+	bz_file.close()
+
+def close_and_open_file(filename, file_obj = None):
+	""" Closes an open file, then re-opens it immediately. """
+
+	try:
+		file_obj.close()
+	except AttributeError:
+		# not created--ignore
+		pass
+	return open(filename, "w")
+