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

前端 未结 15 949
傲寒
傲寒 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:37

    Python 3

    For the directory of the script being run:

    import pathlib
    pathlib.Path(__file__).parent.absolute()
    

    For the current working directory:

    import pathlib
    pathlib.Path().absolute()
    

    Python 2 and 3

    For the directory of the script being run:

    import os
    os.path.dirname(os.path.abspath(__file__))
    

    If you mean the current working directory:

    import os
    os.path.abspath(os.getcwd())
    

    Note that before and after file is two underscores, not just one.

    Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.

    References

    1. pathlib in the python documentation.
    2. os.path 2.7, os.path 3.8
    3. os.getcwd 2.7, os.getcwd 3.8
    4. what does the __file__ variable mean/do?
    0 讨论(0)
  • 2020-11-22 17:38

    IPython has a magic command %pwd to get the present working directory. It can be used in following way:

    from IPython.terminal.embed import InteractiveShellEmbed
    
    ip_shell = InteractiveShellEmbed()
    
    present_working_directory = ip_shell.magic("%pwd")
    

    On IPython Jupyter Notebook %pwd can be used directly as following:

    present_working_directory = %pwd
    
    0 讨论(0)
  • 2020-11-22 17:38

    If you just want to see the current working directory

    import os
    print(os.getcwd)
    

    If you want to change the current working directory

    os.chdir(path)
    

    path is a string containing the required path to be moved. e.g.

    path = "C:\\Users\\xyz\\Desktop\\move here"
    
    0 讨论(0)
提交回复
热议问题