[Tutor] Mac to UNIX and back again (what to do about path)

Wesley Chun wesc@deirdre.org
Tue, 10 Jul 2001 16:03:07 -0700 (PDT)


On Wed, 11 Jul 2001, kevin parks wrote:

> I have some scripts that i want to be able to run on both Mac OS 9 and
> under UNIX (the UNIX distribution on Mac OS X). I've managed to get
> the line endings thing somewhat under control with a little drag an
> drop changer app, but i don't know what to do about the path
> separator. On Mac it is (as you know ':' and UNIX is '/'. I'd really
> like to have one script that works on both.


Kevin,

You have such a well-known and commonly-occurring problem
that all of it has been taken care of by Python's OS module...
you don't even need ':' or '/' in any of your code anymore(!)
nor do you need os.platform for it as ugly and messy as John
indicated in his reply.  The os module has the following 5
file system (string) attributes for you and anyone else with
porting issues to contend with:

Attribute	Description
---------	-----------
linesep		string used to separate lines in a file
sep		string used to separate file pathname components
pathsep		string used to delimit a set of file pathnames
curdir		string name for current working directory
pardir		string name for parent (of current working dir)

If you just "import os" in your script, no matter what platform
that script is running on, the corect string values will be
available in these attributes, i.e., on UNIX, os.sep == '/' and
on the Mac, os.sep == ':', and on Windoze, os.sep == '\\'.

In John's reply, he indicated an intelligent way to join pathnames
into a singleproperly-delimited string like this:

>>path=os.path.join("myfolder", "mysubfolder", "myfile")

I think that he meant using os.sep and a sequence instead:

path=os.sep.join(["myfolder", "mysubfolder", "myfile"])

So no matter who is running this line of code, the "right" thing
will be done...  on the Mac, it'll turn into:

path = ':'.join(["myfolder", "mysubfolder", "myfile"])

(and '/'.join() for UNIX and '\\'.join() for Win)

Here's an example for Windoze:

>>> os.sep.join(['C:', 'a', 'b', 'c'])
'C:\\a\\b\\c'

If you happen to have Core Python Programming, this topic is
discussed in detail in the Core Note on p. 263 in section 9.3.5.

hope this helps!

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Silicon Valley-SF Bay Area Python users group:  http://baypiggies.org

"Core Python Programming", Prentice Hall PTR, December 2000
    http://starship.python.net/crew/wesc/cpp/

wesley.j.chun :: wesc@baypiggies.org
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/