"makepath(path)" creates missing directories for path and returns a normalized absolute version of the path. As often the case with python, the documentation is more important than the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #!/usr/bin/env python
def makepath(path):
""" creates missing directories for the given path and
returns a normalized absolute version of the path.
- if the given path already exists in the filesystem
the filesystem is not modified.
- otherwise makepath creates directories along the given path
using the dirname() of the path. You may append
a '/' to the path if you want it to be a directory path.
from holger@trillke.net 2002/03/18
"""
from os import makedirs
from os.path import normpath,dirname,exists,abspath
dpath = normpath(dirname(path))
if not exists(dpath): makedirs(dpath)
return normpath(abspath(path))
#
#
####### some usages
#
#
if __name__=='__main__':
# simple use
abspath = makepath('tmp/log.txt')
# nice use for making some directories
dirs = map (makepath, ('var/log/', 'var/db/', 'tmp/logfile'))
# nice for just using it like this
file = open(makepath('/tmp/dir/hallo'), 'w')
file.write("hello world\n")
file.close()
|
The usual os.makedirs functions and friends are not convenient enough. They don't return the path and they always throw errors if the directories already exist. Many times you just want to make sure that the directories of a path are really there without the fuss. And you want your directories to be os-independent (e.G. slash versus backslash issues). makepath does all this.
if one of the directory parts of the path already exists and is e.G. a regular file the usual os.makedirs exceptions will be thrown which is ok because your path cannot be constructed.
Expanding the user directory. Holger, thanks for this.
I make extensive use of ~/tmp and other user-directory based paths for a project. makepath did not behave well for those cases, so I added
immediately before
which seems to work fine in testing on OSX.
I also created a mkdirs function using makepath that forces directories.
--r.