简体   繁体   English

在 Python 中获取相对路径的任何优雅方法?

[英]Any elegant way to get relative path in Python?

Say I want to delete 'Core.dll' after 'git pull' , so I write a hook.假设我想在'git pull'之后删除'Core.dll' 'git pull' ,所以我写了一个钩子。

import os

dir = os.path.dirname(__file__)
try:
    os.remove(os.path.abspath(dir+os.sep+".."+os.sep+".."+os.sep+"Assets"+os.sep+"Plugins"+os.sep+"Core.dll"))

except OSError:
    pass

Say the hook path is 'E:\\client\\.git\\hooks' , the file I want to delete is in 'E:\\client\\Assets\\Plugins\\Core.dll'.假设钩子路径是'E:\\client\\.git\\hooks' ,我要删除的文件在'E:\\client\\Assets\\Plugins\\Core.dll'.

I think my way is very silly, is there any elegant way to get the relative path?我觉得我的方法很傻,有没有什么优雅的方法可以得到相对路径?

Using pathlib :使用pathlib

from pathlib import Path

(Path(__file__).absolute().parent.parent.parent/'Assets'/'Plugins'/'Core.dll').unlink()

Antti 的解决方案是 Python 3 中最好的。对于 Python 2,您可以使用os.pardiros.path.join

os.path.abspath(os.path.join(d, os.pardir, os.pardir, "Assets", "Plugins", "Core.dll"))

os.path.relpath would be what you asked for. os.path.relpath就是你所要求的。 You should also be using os.path.join instead of that long list of + and sep.您还应该使用os.path.join而不是 + 和 sep 的长列表。 In Python 3's pathlib, there's relative_to .在 Python 3 的 pathlib 中,有relative_to It appears your code is trying to apply a relative path, not get it in relative form.看来您的代码正在尝试应用相对路径,而不是以相对形式获取它。 In that case, joinpath andnormpath or realpath might help.在这种情况下,joinpath 和normpath或 realpath 可能会有所帮助。

More readable solution:更具可读性的解决方案:

import os 
from contextlib import suppress

with suppress(OSError):
  dir = os.path.dirname(__file__)

  while '.git' in dir:
    dir = os.path.dirname(dir)

  os.remove(
    os.path.join(
      dir,
      'Assets',
      'Plugins',
      'Core.dll'
    )
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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