Os.path: can you explain this behavior?

I love Python because it includes batteries, and I use the built-in functions to do the dirty work for me.

I always enjoyed using the os.path module to work with the file path, but recently I got unexpected results in Python 2.5 under Ubuntu linux, dealing with a line that represents the paths to Windows files:

filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')

WTF?

It ends the same way with the file path = u "c: \ ttemp \ FILEPA ~ 1.EXE" and filepath = "c: \ ttemp \ FILEPA ~ 1.EXE".

Do you have a key? Ubuntu uses UTF8, but I don’t feel that it has anything to do with it. My Python installation may have been confused, but I did not make any special settings that I remember.

+5
3

Windows Linux, ntpath ( , os.path windows - posixpath os.path linux)

>>> import ntpath
>>> filepath = r"c:\ttemp\FILEPA~1.EXE"
>>> print ntpath.basename(filepath)
FILEPA~1.EXE
>>> print ntpath.splitdrive(filepath)
('c:', '\\ttemp\\FILEPA~1.EXE')
+24

os.path:

os.path.splitdrive()
(, ), , . , , . + , .

unix, , - .

Windows- , :

import re
(drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups() 

drive , : (, c:, u:) None, tail :)

+3

. , :

splitdrive (p) Separate the drive path and path. In Posix, the drive is always empty.

Thus, this will not work in the Linux box.

+1
source

All Articles