0

In batch there is a command %~dp0 which mean change the directory to the script directory, for example: Batch file is in desktop, if you use %~dp0 the directory instantly go to the C:\Users\Windows\Desktop without you typing it. Is there any code that do the same as %~dp0 in Python??

BransRma
  • 17
  • 3
  • Not 100% sure if it's the thing you are looking for but `print(__file__)` might be the thing you are looking for? – Leemosh Jan 11 '21 at 07:47

1 Answers1

4

You can implement it through two functions in the os and os.path modules. os.chdir changes the current working directory and os.path.dirname returns the directory name from a file path. __file__ contains the path of the currently running script.

import os

os.chdir(os.path.dirname(__file__))
print(os.getcwd())

.. will output the directory where your script is located.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84