2017-08-11 35 views
3

通过自动完成发现一个pathlib.Path第一种方法是absolute()我可以使用无证方法pathlib.Path.absolute()?

似乎在一开始只是在前面加上Path.cwd()

>>> from pathlib import Path 
>>> path = Path('./relative/path')/'../with/some/../relative/parts' 
Path('relative/path/../with/some/../relative/parts') 
# calling absolute... 
>>> absolute_path = path.absolute() 
Path('/[current_dir]/relative/path/../with/some/../relative/parts') 
# does the same as prepending cwd at the start 
>>> Path.cwd()/path 
Path('/[current_dir]/relative/path/../with/some/../relative/parts') 

然而,Path.absolute()没有在pathlib documentation上市。

比较这对Path.resolve(),它执行相反的(取代的相对的部分,但不预置cwd)和记载。

我可以用absolute()或者我应该避免呢?

回答

3

至少直到Python版本3.6,你应该避免使用Path.absolute()

根据the bug report about the missing documentation讨论, absolute()没有经过测试,因此没有正式公布。事实上,它可能甚至将在未来的Python释放删除。

因此,使用Path.cwd()代替它更安全。

如果您不确定是否真的需要这样做,您可以使用Path.is_absolute()进行检查。

>>> # make path absolute if it isn't already 
>>> path = path if path.is_absolute() else Path.cwd()/path 
Path('/[current_dir]/relative/path/../with/some/../relative/parts') 
相关问题