Suggestion for os.path.join

Tim Peters tim.one at home.com
Wed May 23 19:13:11 EDT 2001


[David Morgenthaler]
> 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.

And it later turns out it's the platform-appropriate '\' you object to, not
the platform-inappropriate '/' hardcoded in your PATH vrbl.

You really don't want platform-independence if you want '/' regardless of
platform:  you want Unix paths, period.  So don't use os.path.join, use the
Unix flavor of join instead:

>>> PATH = 'D:/SARCrates/SARBoxResults'
>>> import posixpath
>>> outfile = posixpath.join(PATH, "subdir", "outfile.PNG")
>>> print outfile
D:/SARCrates/SARBoxResults/subdir/outfile.PNG
>>>

It would be an abomination to make os.path.join pretend every system is Unix
(or Windows, or Mac, or ...).





More information about the Python-list mailing list