os.path.split: processing paths from one OS on another

Hans Nowak hans at zephyrfalcon.org
Tue Jan 27 11:53:13 EST 2004


Martijn Ras wrote:
> Heya folks,
> 
> I ran into the following problem:
> 
> When i run this on Windows everything is as expected:
> C:\>python
> Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import os
>  >>> file='/TEST/FILE.EXT'
>  >>> print os.path.split(file)
> ('/TEST', 'FILE.EXT')
>  >>> file='C:\\TEST\\FILE.EXT'
>  >>> print os.path.split(file)
> ('C:\\TEST', 'FILE.EXT')
> 
> However, when i run this on Linux the results are unexpected:
> $ python
> Python 2.2.3 (#1, Nov 12 2003, 15:53:11)
> [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import os
>  >>> file='/TEST/FILE.EXT'
>  >>> print os.path.split(file)
> ('/TEST', 'FILE.EXT')
>  >>> file='C:\\TEST\\FILE.EXT'
>  >>> print os.path.split(file)
> ('', 'C:\\TEST\\FILE')
> 
> All i can find is some comments on POSIX-ness (or not) of the OS, in 
> regard to os.path.split(), but i fail to see why that explains the 
> different outcome of the last command in the two examples above.

os.path is really a portable layer over platform-specific modules.  Try this 
little experiment:

 >>> import os
 >>> os.path
<module 'ntpath' from 'C:\Python23\lib\ntpath.pyc'>
 >>>

On Windows, os.path is really the ntpath module, but on Linux, you'll see 
'posixpath'.  ntpath and posixpath implement platform-specific rules, for 
example, they deal with the path separator used on a given system.

Windows can deal with both slashes and backslashes as separators, but posix 
(apparently) only accepts slashes:

 >>> import ntpath, posixpath
 >>> ntpath.split("c:/foo/bar.txt")
('c:/foo', 'bar.txt')
 >>> ntpath.split("c:\\foo\\bar.txt")
('c:\\foo', 'bar.txt')
 >>> posixpath.split("c:/foo/bar.txt")
('c:/foo', 'bar.txt')
 >>> posixpath.split("c:\\foo\\bar.txt")
('', 'c:\\foo\\bar.txt')

> My server needs to be run on either Linux or Windows, it receives 
> requests from clients that may run either OS. To process those requests 
> i need to split the path and filename. I hoped to solves this using 
> os.path.split (), any suggestions as to how to fix this?

One possible solution is to always use forward slashes for literal paths. 
These should work on both Linux and Windows.  If necessary, you can convert 
backslashes to forward slashes before processing.  It's easy enough:

 >>> string.replace("c:\\foo\\bar.txt", "\\", "/")
'c:/foo/bar.txt'
 >>>

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/






More information about the Python-list mailing list