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

前端 未结 15 947
傲寒
傲寒 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:11
    ## IMPORT MODULES
    import os
    
    ## CALCULATE FILEPATH VARIABLE
    filepath = os.path.abspath('') ## ~ os.getcwd()
    ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
    ## ..OR DIFFERENT IN SOME CIRCUMSTANCES
    
    0 讨论(0)
  • 2020-11-22 17:12

    To keep the migration consistency across platforms (macOS/Windows/Linux), try:

    path = r'%s' % os.getcwd().replace('\\','/')
    
    0 讨论(0)
  • 2020-11-22 17:21
    import os
    print os.path.dirname(__file__)
    
    0 讨论(0)
  • 2020-11-22 17:22

    Using Path is the recommended way since Python 3:

    from pathlib import Path
    print("File      Path:", Path(__file__).absolute())
    print("Directory Path:", Path().absolute())  
    

    Documentation: pathlib

    Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.

    0 讨论(0)
  • 2020-11-22 17:22

    I found the following commands will all return the full path of the parent directory of a Python 3.6 script.

    Python 3.6 Script:

    #!/usr/bin/env python3.6
    # -*- coding: utf-8 -*-
    
    from pathlib import Path
    
    #Get the absolute path of a Python3.6 script
    dir1 = Path().resolve()  #Make the path absolute, resolving any symlinks.
    dir2 = Path().absolute() #See @RonKalian answer 
    dir3 = Path(__file__).parent.absolute() #See @Arminius answer 
    
    print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}')
    

    Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()

    0 讨论(0)
  • 2020-11-22 17:24

    Let's assume you have the following directory structure: -

    main/ fold1 fold2 fold3...

    folders = glob.glob("main/fold*")
    
    for fold in folders:
        abspath = os.path.dirname(os.path.abspath(fold))
        fullpath = os.path.join(abspath, sch)
        print(fullpath)
    
    0 讨论(0)
提交回复
热议问题