ThatNewGuy
ThatNewGuy

Reputation: 197

Why is the absolute path of a drive letter equal to the working directory?

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:

Using os.path.abspath

os.path.abspath('.') prints 'C:\\Users\\myuser'

os.path.abspath('C:') also prints 'C:\\Users\\myuser'

Using 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

Using 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'

Using a different drive letter

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.

Conclusion

So what's going on here? Why is 'C:' treated as '.\\'?

Additional Notes

Upvotes: 0

Views: 2007

Answers (1)

Kemp
Kemp

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

Related Questions