简体   繁体   中英

Python path - handling home AND relative directory

I'm trying to get the absolute path from a user input so there's no ambiguity within my script. I need to be able to handle both paths ~/Documents/repos/project and ./project .

Libraries like os.path and pathlib are able to resolve both cases - for example, in pathlib , expanduser resolves ~ and resolve() figures out relative paths, but neither can do both at the same time.

To elaborate, expanduser will strip relative paths of any periods, and resolve() will incorrectly resolve paths containing ~ . This means that combining the two will leave me with an incorrect path.

I could simply replace ~ with Path.home() , and then resolve the path, but I'm wondering if there's a "more correct", or simpler way to achieve this.

You can use os.path.abspath and os.path.expanduser together:

/var/tmp $ python
>>> from os.path import abspath, expanduser
>>> abspath(expanduser("./bar"))
'/var/tmp/bar'
>>> abspath(expanduser("~/foo"))
'/home/my.username/foo'

The pathlib method:

>>> PosixPath('./bar').expanduser().resolve()
PosixPath('/var/tmp/bar')
>>> PosixPath('~/foo').expanduser().resolve()
PosixPath('/home/my.username/foo')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM