OS independent files

Larry Bates larry.bates at websafe.com
Thu Aug 3 15:36:24 EDT 2006


crystalattice wrote:
> I'm sure this has been addressed before but it's difficult to search
> through several thousand postings for exactly what I need, so I
> apologize if this a redundant question.
> 
> I've figured out how to use os.path.join to make a file or directory
> location prior to pickling something to it.  But I have a question
> about it.  In Windows I can make a file with this:
> 
> os.path.join("C:", "myfiles", "myfile.dat")
> 
> If I want to make sure the file/directory is made in a user's home
> directory (e.g. /home/users/path/to/file) but also compatible w/
> Windows, how would I rewrite this (if required)?
> 
I don't believe there is an "automatic" way to do this, but you can
check which OS you are running under and branch accordingly.  For
examples on how to do this take a look at /lib/os.py source code that
comes with Python.  It seems to check sys.builtin_module_names to
determine which OS it is running on.  Then you can use os.path.join()
to build path to your "home" directory.  You will probably also need
to look at os.environ to get some info from the user's environment.
The "trickiest" part will be to find what code is necessary to track
down the users "home directory" on each different operating system.

Hope this helps.

-Larry Bates



More information about the Python-list mailing list