【问题标题】:How do I get the full path of the current file's directory?如何获取当前文件目录的完整路径?
【发布时间】:2011-03-26 17:08:25
【问题描述】:

我想获取当前文件的目录路径。 我试过了:

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

但是我怎样才能检索目录的路径呢?

例如:

'C:\\python27\\'

【问题讨论】:

  • __file__ 在将 python 作为交互式 shell 运行时未定义。您问题中的第一段代码看起来像是来自交互式外壳,但实际上会产生一个NameError,至少在 python 2.7.3 上,但我猜其他的也是。
  • 为什么。是。这。所以。难的。关于这个主题有十几个 SO 主题。 Python:“简单胜于复杂……应该有一种——最好只有一种——明显的方法。”

标签: python directory


【解决方案1】:

特殊变量__file__ 包含当前文件的路径。从中我们可以使用Pathlibos.path 模块获取目录。

Python 3

对于正在运行的脚本的目录:

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

对于当前工作目录:

import pathlib
pathlib.Path().resolve()

Python 2 和 3

对于正在运行的脚本的目录:

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

如果你指的是当前工作目录:

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

请注意,file 之前和之后是两个下划线,而不仅仅是一个。

另外请注意,如果您以交互方式运行或从文件以外的东西(例如:数据库或在线资源)加载代码,则可能不会设置__file__,因为没有“当前文件”的概念。上面的答案假设最常见的情况是运行文件中的 python 脚本。

参考文献

  1. pathlib 在 python 文档中。
  2. os.path - Python 2.7, os.path - Python 3
  3. os.getcwd - Python 2.7, os.getcwd - Python 3
  4. what does the __file__ variable mean/do?

【讨论】:

  • abspath() 如果您不想在 Windows 上发现奇怪的行为,则必须使用,其中 dirname(file) 可能会返回一个空字符串!
  • 应该是os.path.dirname(os.path.abspath(os.__file__))?
  • @DrBailey:不,ActivePython 没有什么特别之处。 __file__(注意它的两边是两个下划线)是python的标准部分。例如,它在基于 C 的模块中不可用,但它应该始终在 python 脚本中可用。
  • 我建议使用 realpath 而不是 abspath 来解析可能的符号链接。
  • @cph2117:只有在脚本中运行它才会起作用。如果从交互式提示运行,则没有 __file__。 \
【解决方案2】:
import os
print os.path.dirname(__file__)

【讨论】:

  • 对不起,这个答案不正确,正确的是 Bryan `dirname(abspath(file)) 的答案。有关详细信息,请参阅 cmets。
  • 它将给出/ 作为输出
  • @sorin 实际上在 Python 3.6 上它们都是一样的
【解决方案3】:

IPython 有一个魔术命令%pwd 来获取当前工作目录。可以通过以下方式使用:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

在IPython Jupyter Notebook %pwd可以直接使用如下:

present_working_directory = %pwd

【讨论】:

  • 问题不在于 IPython
  • @Kiro,我的解决方案 回答了问题 使用 IPython。例如,如果有人使用新库的解决方案来回答问题,那么恕我直言,它仍然是对该问题的相关答案。
  • @elli0t,部分同意。考虑使用 Jupyter notebook 的人有这个问题,也许使用 %pwd 魔法命令比 os import 更容易和更可取。
  • 问题不在于获取当前的工作目录,而在于获取脚本的目录。这两者可能是非常不同的东西。
  • @NafeezQuraishi:我不明白你的意思。问题显然是询问文件所在目录的路径,该目录可能不是当前工作目录。这是两个不同的概念。
【解决方案4】:

使用 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

注意:如果使用 Jupyter Notebook,__file__ 不会返回预期值,因此必须使用 Path().absolute()

【讨论】:

  • 我必须通过Path(__file__).parent 获取包含该文件的文件夹
  • 这是正确的@YellowPillow,Path(__file__) 为您获取文件。 .parent 让你上一层,即包含目录。您可以在其中添加更多 .parent 以根据需要添加任意数量的目录。
  • 抱歉,我应该更清楚地说明这一点,但如果 Path().absolute() 存在于位于 path/to/module 的某个模块中,并且您正在从位于 path/to/script 的某个脚本中调用该模块,那么将返回path/to/script 而不是 path/to/module
  • @YellowPillow Path(__file__).cwd() 更明确
  • Path(__file__) 并不总是有效,例如,它在 Jupyter Notebook 中无效。 Path().absolute() 解决了这个问题。
【解决方案5】:

我已经制作了一个函数,用于在 CGI 中的 IIS 下运行 python 以获取当前文件夹:

import os 
def getLocalFolder():
    path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
    return path[len(path)-1]

【讨论】:

    【解决方案6】:

    在 Python 3.x 中我会这样做:

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

    解释:

    • Path(__file__) 是当前文件的路径。
    • .parent 为您提供文件所在的目录
    • .absolute() 为您提供完整的绝对路径。

    使用pathlib 是处理路径的现代方式。如果您稍后出于某种原因需要它作为字符串,只需执行str(path)

    【讨论】:

    • 这应该是 2019 年公认的答案。答案中还可以提到一件事:可以立即在 Path 这样的 .open() 对象上调用 .open(),如 with Path(__file__).parent.joinpath('some_file.txt').open() as f:跨度>
    • 一些答案​​的另一个问题(如果我没记错的话,比如来自 Ron Kalian 的那个),它会给你当前目录,不一定是 file 路径。
    【解决方案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))
    

    输出: 绝对路径是放置 Python 文件的路径

    绝对路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib 和 seaborn Part2

    文件路径:D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib 和 seaborn Part2\data\fuel_econ.csv

    isfileExist : 真

    isadirectory : 假

    文件扩展名:.csv

    【讨论】:

    • 谢谢。在 JupyterLab 中也能完美运行
    • 这是误导,绝对是 cwd 不是您的文件所在的位置。不保证相同。
    • Path() 是当前工作目录,不是脚本所在目录。这仅在脚本实际位于当前工作目录中的少数情况下“有效”。
    【解决方案8】:

    试试这个:

    import os
    dir_path = os.path.dirname(os.path.realpath(__file__))
    

    【讨论】:

    • 最佳答案。这是我通常获取当前脚本路径的方式,谢谢。
    【解决方案9】:

    我发现以下命令返回 Python 3 脚本的父目录的完整路径。

    Python 3 脚本:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    from pathlib import Path
    
    #Get the absolute path of a Python3.6 and above 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
    dir4 = Path(__file__).parent 
    
    print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')
    

    备注!!!!

    1. dir1dir2 仅在运行位于当前工作目录中的脚本时有效,但在任何其他情况下都会中断。
    2. 鉴于Path(__file__).is_absolute()True,在dir3 中使用.absolute() 方法显得多余。
    3. 有效的最短命令是 dir4

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

    【讨论】:

    • 一个裸露的Path()提供脚本/模块目录。它相当于Path('.')——当前工作目录。这仅在运行位于当前工作目录中的脚本时是等效的,但在任何其他情况下都会中断。
    • @MisterMiyagi 我已更新您对我的回答的评论。谢谢。
    猜你喜欢
    • 2010-10-11
    • 2014-05-18
    • 2010-10-15
    • 2013-11-12
    • 1970-01-01
    • 2015-09-23
    • 2014-02-09
    • 2014-04-18
    相关资源
    最近更新 更多