Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any elegant way to get relative path in Python?

Tags:

python

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?

like image 577
Tim Avatar asked Jan 03 '23 07:01

Tim


1 Answers

Using pathlib:

from pathlib import Path

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