Suggestion for os.path.join

David Morgenthaler boogiemorg at aol.com
Wed May 23 18:18:05 EDT 2001


We use os.path.join() extensively to keep our code platform
independent. But we sometimes have problems on win32 when the
resulting path is passed to a C-extension -- not all C-extensions
(e.g., gdchart) are smart enough to handle the result.

Example:
Python 2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> PATH = 'D:/SARCrates/SARBoxResults'
>>> import os
>>> outfile = os.path.join(PATH,"subdir","outfile.png")
>>> print outfile
D:/SARCrates/SARBoxResults\subdir\outfile.png
>>>

The combination of '/'s and '\'s in the resulting path are not handled
by gdchart.chart. I have similar problems with the PIL's ImageFont,
etc.

Suggestion: Change ntpath.join to give join a signature of something
like os.path.join(path [, path2 [, ...]], [sep=s]). The following
should do the trick.

def join(a, *p, **parms):
    """Join two or more pathname components, inserting "\\" or sep as
needed"""
    if parms.has_key('sep'):
        sep = parms['sep']
    else:
        sep = "\\"
    path = a
    for b in p:
        if isabs(b):
            path = b
        elif path == '' or path[-1:] in '/\\:':
            path = path + b
        else:
            path = path + sep + b
    return path


Then I get the following behavior, solving my problem:

>>> PATH = 'D:/SARCrates/SARBoxResults'
>>> outfile = join(PATH,"subdir","outfile.png")
>>> print outfile
D:/SARCrates/SARBoxResults\subdir\outfile.png
>>> outfile = join(PATH,"subdir","outfile.png",sep='/')
>>> print outfile
D:/SARCrates/SARBoxResults/subdir/outfile.png
>>>

join for other platforms could simply ignore the separator parameter.

David



More information about the Python-list mailing list