How do I get the full path of the current file's directory?

前端 未结 15 1135
傲寒
傲寒 2020-11-22 17:01

I want to get the current file\'s directory path. I tried:

>>> os.path.abspath(__file__)
\'C:\\\\python27\\\\test.py\'

But how can

15条回答
  •  半阙折子戏
    2020-11-22 17:33

    In Python 3.x I do:

    from pathlib import Path
    
    path = Path(__file__).parent.absolute()
    

    Explanation:

    • Path(__file__) is the path to the current file.
    • .parent gives you the directory the file is in.
    • .absolute() gives you the full absolute path to it.

    Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).

提交回复
热议问题