What's the perfect (OS independent) way of storing filepaths ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Oct 19 17:30:30 CEST 2008

On Sun, 19 Oct 2008 14:35:01 +0200, Stef Mientki wrote:

> hello,
> I (again) wonder what's the perfect way to store, OS-independent,
> filepaths ?

"Perfect"? I can't imagine any scheme which will work on every imaginable 
OS, past present and future.

However, in practice I think there are two common forms still in use: 
Posix paths, and Windows paths. I believe that OS/2 can deal with Windows 
pathnames, and Mac OS X uses Posix paths (I think...). If you have to 
support Classic Mac OS or other non-Posix systems, then your life will 
become interesting and complicated.

And let's not even consider Unicode issues...

You might find this page useful:

Note that raw strings are for regular expressions, not Windows paths. Raw 
strings can't end in a backslash, so you can't do this:

r'C:\My Documents\'

Instead, you can avoid having to escape backslashes by taking advantage 
of the fact that Windows will accept forward slashes as well as 
backslashes as path separators, and write 'C:/My Documents/' instead.

I assume you're familiar with the path-manipulation utilities in os.path?

>>> import os
>>> os.path.splitdrive('C://My Documents/My File.txt')
('C:\\\\', 'My Documents\\My File.txt')

I had to fake the above output because I'm not running Windows, so excuse 
me if I got it wrong.

But honestly, I think your biggest problem isn't finding a platform-
independent way of storing paths, but simply translating between each 
OS's conventions on where files should be stored.

In Linux, config files should go into:

~/.<appname>/ or /etc/<appname>/

In Windows (which versions?) then should go into the Documents And 
Settings folder, where ever that is.

There's no single string which can represent both of these conventions!


More information about the Python-list mailing list