Issue:
>>> from pathlib import Path
>>> Path('C:').absolute().is_absolute() # Is 'C:' absolute if we try to make it with pathlib?
False
>>> os.path.isabs(os.path.abspath('C:')) # Is 'C:' absolute if we try to make it with os.path?
True
>>> os.path.isabs('C:') # Is 'C:' absolute on it's own?
False
# Correct way to get absolute path as suggested in answers below
>>> Path('C:').resolve()
WindowsPath('C:/Windows/system32') # We get a folder we have launched Python from
- How comes
Path.absolute()
returns a non-absolute path? - Who's right, who's wrong?
- Bonus quesion: Which function wraps windows' drive letter
(C:)
to path(C:\\)
, soos.path.join
would work properly?
Example:
Try to get a file path out of a 'path' and 'filename', and given the file finds itself in root of a Windows OS disk, you'll have trouble creating a path that is functional
>>> a_path = 'C:'
>>> a_file_name = 'foo.txt'
>>> os.path.join(a_path, a_file_name)
'C:foo.txt'
>>> os.path.isabs(os.path.abspath('C:'))
True
and to add a pinch of confusion, if you create the file at C:\foo.txt prior; you'll get:
>>> os.path.exists('C:foo.txt')
False
>>> os.path.exists(os.path.abspath('C:foo.txt'))
False
Alternative execution with the pathlib
>>> from pathlib import Path
>>> Path('C:').joinpath('foo.txt')
WindowsPath('C:too.txt')
>>> Path('C:').joinpath('foo.txt').is_absolute()
False
Real life situation:
Apparently, Cinema4D's Python SDK method doc.GetDocumentPath()
returns in fact C:
if the document in question is located in the root folder on the C: drive.
Related quesions: