为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用pathlib处理以~开头的路径?

如何使用pathlib处理以~开头的路径?

Qyouu 2023-08-15 16:46:22
我正在编写一个 cli 工具,需要一些路径作为输入。我正在用 python 编写这个工具,并且不想使用 3.6 以下的 python 解释器。使用包pathlib似乎是处理 python 中的路径时的现代方法。所以如果可能的话我想离开os并os.path留下来。看起来 pathlib 将路径解释~/test/为当前工作目录的相对路径,下面的代码显示了它import pathlibtest_path = pathlib.Path('~/test')absolute_path = test_path.absolute()print(f"{str(test_path):>31}\n{str(absolute_path):>31}")# output:#              ~/test# /home/myUser/~/test如何使用 pathlib 识别以~绝对路径开头的每个路径并自动扩展~到用户主目录?
查看完整描述

1 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

答案很简单,.expanduser()在 Path 对象上使用而不是.absolute(),它会将 ~ 替换为运行脚本的用户的主目录,仅当 ~ 位于开头时,结果也是绝对路径:


import pathlib


test_path = pathlib.Path('~/test')

absolute_path = test_path.expanduser()

# If ~ is somewhere in the middle of the path, use .resolve() to get an absolute path.


print(f"{str(test_path):>31}\n{str(absolute_path):>31}")

# output:

#            ~/test

# /home/myUser/test


查看完整回答
反对 回复 2023-08-15
  • 1 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信