Joh*_*ohn 3 python python-3.x pathlib
我有一个pathlib.Path('/etc')。如果我需要为其添加前缀pathlib.Path('/mnt/chroot')并执行以下操作:
Path('/mnt/chroot') / Path('/etc')
我最终得到: PosixPath('/etc'),大概是因为两者Path都是绝对路径,并且不能连接。
我可以用类似的方法来组合解决方案:
Path('/mnt/chroot') / str(Path('/etc')).removeprefix('/')
但这是冗长、粗俗的。有没有更简单、正确的方法来做到这一点?
您可以Path('/etc')使用以下方法将其转换为相对路径relative_to:
Path('/mnt/chroot') / Path('/etc').relative_to('/')
Run Code Online (Sandbox Code Playgroud)