Reputation: 117
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
Path.absolute()
returns a non-absolute path?(C:)
to path (C:\\)
, so os.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:
Upvotes: 2
Views: 826
Reputation: 281683
The absolute()
method isn't actually part of the pathlib.Path
documented public API. It doesn't really work, and you're not supposed to use it. It's got comments in its source code saying stuff like "XXX untested yet!" and "FIXME".
The actual, documented method for getting an absolute path is Path.resolve()
. I think that one should behave correctly for this input... but I think "behave correctly" means returning an absolute path to your current working directory on the C drive. I don't think it's going to return 'C:\\'
. Also, unlike os.path.abspath
, Path.resolve
requires a path that actually resolves to something, and it'll also resolve symbolic links.
If you want something that behaves like os.path.abspath
, use os.path.abspath
. Pathlib does not support a direct equivalent of that function.
Upvotes: 3