How do you properly determine the current script directory in Python?

后端 未结 12 1658
情深已故
情深已故 2020-11-22 02:30

I would like to see what is the best way to determine the current script directory in Python.

I discovered that, due to the many ways of calling Python code, it is ha

12条回答
  •  渐次进展
    2020-11-22 02:49

    In Python 3.4+ you can use the simpler pathlib module:

    from inspect import currentframe, getframeinfo
    from pathlib import Path
    
    filename = getframeinfo(currentframe()).filename
    parent = Path(filename).resolve().parent
    

    You can also use __file__ to avoid the inspect module altogether:

    from pathlib import Path
    parent = Path(__file__).resolve().parent
    

提交回复
热议问题