代码之家  ›  专栏  ›  技术社区  ›  Shubham

如何在Python中获得当前文件目录的完整路径?

  •  561
  • Shubham  · 技术社区  · 16 年前

    我试过:

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

    例如:

    'C:\\python27\\'
    
    11 回复  |  直到 7 年前
        1
  •  2026
  •   Bryan Oakley    6 年前

    蟒蛇3

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

    对于当前工作目录:

    import pathlib
    pathlib.Path().absolute()
    

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

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

    file 是两个下划线,而不仅仅是一个。

    还要注意的是,如果您是以交互方式运行的,或者从文件以外的其他地方(例如:数据库或联机资源)加载了代码, __file__

    工具书类

    1. pathlib 在python文档中。
    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?
        2
  •  122
  •   NotAnAmbiTurner    5 年前

    使用 Path 是自Python 3以来推荐的方法:

    from pathlib import Path
    print("File      Path:", Path(__file__).absolute())
    print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__  
    

    文档: pathlib

    __file__ 不返回期望值,所以 Path().absolute()

        3
  •  61
  •   Arminius    7 年前

    在Python3.x中,我有:

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

    说明:

    • Path(__file__) 是当前文件的路径。
    • .parent 给你机会 目录
    • .absolute() 给你机会 完全绝对

    使用 pathlib str(path) .

        4
  •  11
  •   chefsmart    16 年前
    import os
    print os.path.dirname(__file__)
    
        5
  •  9
  •   Akshaya Natarajan    7 年前

    试试这个:

    import os
    dir_path = os.path.dirname(os.path.realpath(__file__))
    
        6
  •  3
  •   Nafeez Quraishi    8 年前

    IPython 有一个神奇的命令 %pwd 获取当前工作目录。可按以下方式使用:

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

    在IPython Jupyter笔记本上 可直接使用如下:

    present_working_directory = %pwd
    
        7
  •  3
  •   Arpan Saini    7 年前

    PYTHON中有用的路径属性:

     from pathlib import Path
    
        #Returns the path of the directory, where your script file is placed
        mypath = Path().absolute()
        print('Absolute path : {}'.format(mypath))
    
        #if you want to go to any other file inside the subdirectories of the directory path got from above method
        filePath = mypath/'data'/'fuel_econ.csv'
        print('File path : {}'.format(filePath))
    
        #To check if file present in that directory or Not
        isfileExist = filePath.exists()
        print('isfileExist : {}'.format(isfileExist))
    
        #To check if the path is a directory or a File
        isadirectory = filePath.is_dir()
        print('isadirectory : {}'.format(isadirectory))
    
        #To get the extension of the file
        fileExtension = mypath/'data'/'fuel_econ.csv'
        print('File extension : {}'.format(filePath.suffix))
    

    输出:

    绝对路径:D:\Study\Machine Learning\Jupitor notebooktest2\Udacity\u Scripts\Matplotlib and seaborn Part2

    文件路径:D:\Study\Machine Learning\Jupitor notebooktest2\JupytorNotebookTest2\Udacity\u Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv

    isfileExist:真

    isadirectory:错误

    文件扩展名:.csv

        8
  •  3
  •   Sun Bear    6 年前

    #!/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}')
    

    说明链接: .resolve() , .absolute() , Path( file ).parent().absolute()

        9
  •  2
  •   Alejandro Galera    5 年前

    你可以用 os os.path 如下所示

    import os
    os.chdir(os.path.dirname(os.getcwd()))
    

    os.path.dirname 从当前目录返回上层目录。 它允许我们在不传递任何文件参数和不知道绝对路径的情况下切换到更高的级别。

    os.path.dirname(os.path.abspath(myfilename))

        10
  •  1
  •   Qiao Zhang    8 年前

    要保持跨平台(macOS/Windows/Linux)迁移的一致性,请尝试:

    path = r'%s' % os.getcwd().replace('\\','/')
    
        11
  •  1
  •   Gil Allen    7 年前

    为了获取当前文件夹,我在CGI中的IIS下运行python时使用了一个函数:

    import os 
       def getLocalFolder():
            path=str(os.path.dirname(os.path.abspath(__file__))).split('\\')
            return path[len(path)-1]
    
        12
  •  1
  •   Jerusalem Programmer    7 年前
    ## 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
    
        13
  •  1
  •   dpacman    6 年前

    假设您有以下目录结构:-

    折叠1 折叠2 折叠3。。。

    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)
    
        14
  •  0
  •   majid bhatti    5 年前

    如果您只想查看当前的工作目录

    import os
    print(os.getcwd())
    

    如果要更改当前工作目录

    os.chdir(path)
    

    path是包含要移动的所需路径的字符串。

    path = "C:\\Users\\xyz\\Desktop\\move here"
    
        15
  •  -1
  •   ForceVII Pythonidae    6 年前

    系统:MacOS

    import os
    
    rootpath = os.getcwd()
    
    os.chdir(rootpath)