4

Say I want to delete 'Core.dll' after 'git pull', so I write a hook.

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'.

I think my way is very silly, is there any elegant way to get the relative path?

3
  • 1
    using os.path.join and os.pardir would be better Commented Oct 16, 2017 at 8:11
  • / will work as a directory separator on all platforms where you'd use both git and python... But also, on Python 3, see pathlib. If on Python 2 -> switch to Python 3. Commented Oct 16, 2017 at 8:11
  • also don't overload dir. Commented Oct 16, 2017 at 8:48

4 Answers 4

6

Using pathlib:

from pathlib import Path

(Path(__file__).absolute().parent.parent.parent/'Assets'/'Plugins'/'Core.dll').unlink()
Sign up to request clarification or add additional context in comments.

1 Comment

I believe the call to absolute() is needed iff __file__ is a relative path... because of a stupid feature in Pathlib that it doesn't traverse past the parent.
3

Antti's solution is the best in Python 3. For Python 2, you could use os.pardir and os.path.join:

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

Comments

1

os.path.relpath would be what you asked for. You should also be using os.path.join instead of that long list of + and sep. In Python 3's pathlib, there's relative_to. It appears your code is trying to apply a relative path, not get it in relative form. In that case, joinpath and normpath or realpath might help.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.