Reputation: 197
I'm experiencing very strange behavior with python's os.path
module. The drive letter of the working directory is treated as a relative path to the working directory itself. For example:
os.path.abspath
os.path.abspath('.')
prints 'C:\\Users\\myuser'
os.path.abspath('C:')
also prints 'C:\\Users\\myuser'
os.path.join
os.path.join('.','Users','myuser')
gives the expected '.\\Users\\myuser'
Notice '\\'
is inserted between all three entries. However:
os.path.join('C:','Users','myuser')
gives 'C:Users\\myuser'
Notice the lack of '\\'
being inserted between C:
and Users
os.path.abspath
with os.path.join
Despite the lack of '\\'
, python accepts 'C:Users'
and treats it as '.\\Users'
as seen here:
'os.path.abspath(os.path.join('C:','Users','myuser'))
gives 'C:\\Users\\J34688\\Users\\myuser'
which is the same as
'os.path.abspath(os.path.join('.','Users','myuser'))
gives 'C:\\Users\\J34688\\Users\\myuser'
This unexpected behavior is not seen when using other drives. For example:
os.path.abspath(os.path.join('D:','Users','myuser'))
gives
'D:\\Users\\myuser'
Which to me seems far more reasonable.
So what's going on here? Why is 'C:'
treated as '.\\'
?
'C:\\'
, which will be treated as the actual letter drive. Still, in every other situation, the '\\'
is optional (e.g. '.'
is equivalent to '.\\'
, and 'D:'
is equivalent to 'D:\\'
).cd
to another directory within the C:
drive, then 'C:'
will refer to that new directory just as '.'
does. Furthermore, if you change to a different drive (say, D:
), then 'C:'
will function as expected and the new letter will be take on this behavior (e.g. 'D:'
is now equivalent to '.'
).Upvotes: 0
Views: 2007
Reputation: 3649
os.path.abspath
calls GetFullPathName
in the Windows API. The documentation for that states that
If you specify "U:" the path returned is the current directory on the "U:" drive
This is just how Windows handles paths, not related to Python.
The documentation for os.path.join
also states
Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.
Upvotes: 2