Welcome, guest | Sign In | My Account | Store | Cart

"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.

Python, 42 lines
 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.

1 comment

Russ Ferriday 14 years, 9 months ago  # | flag

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

path=expanduser(path)

immediately before

dpath = normpath(dirname(path))

which seems to work fine in testing on OSX.

I also created a mkdirs function using makepath that forces directories.

def mkdirs(path):
    """ensures that all elements are created as directories, see makepath().

    Doctest
    =======

    setup
    >>> tmpdir = os.tempnam(None,'dir')
    >>> os.mkdir(tmpdir)

    simple use
    >>> abspath = mkdirs(os.path.join(tmpdir, 'subdir'))
    >>> assert abspath.startswith(tmpdir)
    >>> assert abspath.endswith('subdir')

    nice use for making some directories
    >>> dirs = map (mkdirs, ( os.path.join(tmpdir, 'var/log/'),\
                                os.path.join(tmpdir,'var/db/'),\
                                os.path.join(tmpdir,'tmp/logfile')))
    >>> os.listdir(tmpdir)
    ['subdir', 'tmp', 'var']
    >>> os.listdir(os.path.join(tmpdir,'var'))
    ['db', 'log']

    NOTE: no '/' at end of string - got a subdir anyway!
    >>> os.listdir(os.path.join(tmpdir,'tmp'))
    ['logfile']

    """
    return(makepath(path+'/'))

--r.

Created by H. Krekel on Sun, 17 Mar 2002 (PSF)
Python recipes (4591)
H. Krekel's recipes (4)

Required Modules

Other Information and Tasks