Python Forum
PurePath.relative_to() fails in 3.6
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PurePath.relative_to() fails in 3.6
#6
From docs:
Quote:Note

Although os.path.relpath() and PurePath.relative_to() have some overlapping use-cases, their semantics differ enough to warrant not considering them equivalent.

You can use monkey patching.

from pathlib import Path
from os.path import relpath

Path.relpath = lambda self, start=None: Path(relpath(self, start))

# or define a function
def rp(self, start=None):
    return Path(relpath(self, start))
# Path.relpath = rp

my_path = Path.home() / '.local' / 'bin'
rel = my_path.relpath('/var/log/nginx')
print(my_path)
print(rel)
Output:
/home/deadeye/.local/bin ../../../home/deadeye/.local/bin
Windows:
from pathlib import Path
from os.path import relpath
from os import environ


Path.relpath = lambda self, start=None: Path(relpath(self, start))
 
# or define a function
def rp(self, start=None):
    return Path(relpath(self, start))
# Path.relpath = rp

# Windows has some special Paths stored in environment variables
PROGRAMFILES = Path(environ['PROGRAMFILES'])
LOCALAPPDATA = Path(environ['LOCALAPPDATA'])


rel_prog_path = 'Testprogramm/data'
curdir = PROGRAMFILES / rel_prog_path 
target = LOCALAPPDATA / rel_prog_path 

print(curdir)
print(target)
print(target.relpath(curdir))
Maybe someone can try this on Mac. I don't have Mac.
I guess it's similar to UNIX.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
PurePath.relative_to() fails in 3.6 - by Skaperen - Sep-30-2019, 04:19 AM
RE: PurePath.relative_to() fails in 3.6 - by DeaD_EyE - Oct-18-2019, 06:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Path or PurePath Skaperen 2 7,988 Jul-06-2018, 02:06 AM
Last Post: Skaperen
  Path.relative_to() and symlinks Skaperen 0 2,883 Jun-07-2018, 03:19 AM
Last Post: Skaperen
  getting a full path string from a pathlib.PurePath object Skaperen 14 158,600 Mar-24-2018, 03:55 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020