Entry
Recursive "touch"
Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 164, Preston Landers
"""
Packages: operating_systems.unix
"""
"""
> Anyone know of a function equilivent in concept to a 'recursive
> touch?'
>
> Where if I say:
>
> touch foo/bar/baz.txt
>
> If the directories foo and bar don't exist, create them, then create
> baz.txt inside of bar.
>
> An equivilent unix command would suffice.
"""
"""
Sorry to answer my own question, but I wrote a primitive little
implementation of my request pending discovery of 'the official
version.' Note that mine actually uses the unix touch command but it
could easily be modified to use the more portable python open(file, "w")
"""
import os, string, commands
try:
class execution_exception(Exception): pass
except TypeError:
execution_exception = "execution_exception"
# try-except added by PSST
def recursive_touch_helper(path):
"""A helper function for recursive_touch. Given a path, calls
itself recursively until entire path exists, and returns the same path
string. If something went wrong, it returns None."""
path_list = []
path_elements = string.split(path, "/")[1:]
counter = 1
for element in path_elements:
new_element = ""
for component in range(counter):
new_element = new_element + "/%s" % path_elements[component]
path_list.append(new_element)
counter = counter + 1
for path in path_list:
# see if it exists
if os.path.isdir(path):
continue
# else try to mkdir it
else:
try:
print "making %s" % path
os.mkdir(path)
except OSError, msg:
return None
return path
def recursive_touch(filename):
"""Tries to create filename with unix touch commands. It is
recursive in the sense that any directory components of filename will
be silently created (if possible) before touching the actual file.
throws execution_exception if any part of the operation fails. FYI:
this is not technically a 'recursive funtion'; it just behaves in a
recursive manner."""
pathname, basename = os.path.split(filename)
# check if we're already good to go
if os.path.isfile(filename):
return
if not os.path.isdir(pathname):
if recursive_touch_helper(pathname) != pathname:
raise execution_exception, "Could not create path."
status, output = commands.getstatusoutput("touch %s" % filename)
if status:
raise execution_exception, "could not touch %s" % filename
else:
return # success
path = "/usr/home/planders/tmp/foo/bar/baz.txt"
try:
recursive_touch(path)
except execution_exception, msg:
print "Failed. \n%s" % msg
print "Success."