Home > Enterprise >  Python path - handling home AND relative directory
Python path - handling home AND relative directory

Time:12-13

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.

CodePudding user response:

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')
  • Related