【问题标题】:Find the current directory and file's directory [duplicate]查找当前目录和文件的目录[重复]
【发布时间】:2011-07-05 11:34:03
【问题描述】:

在 Python 中,我可以使用哪些命令来查找:

  1. 当前目录(我在终端中运行 Python 脚本时所在的位置),并且
  2. 我正在执行的文件在哪里?

【问题讨论】:

    标签: python directory


    【解决方案1】:

    要获取包含 Python 文件的目录的完整路径,请将以下内容写入该文件:

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

    (请注意,如果您已经使用 os.chdir() 更改当前工作目录,则上面的咒语将不起作用,因为 __file__ 常量的值是相对于当前工作目录的,并且不会被一个os.chdir() 电话。)


    要获取当前工作目录,请使用

    import os
    cwd = os.getcwd()
    

    上面使用的模块、常量和函数的文档参考:

    【讨论】:

    • 当我使用它附加到 sys.path 时,我讨厌它。我现在觉得很脏。
    • 如果从 IDE(比如 IDLE)调用 file 将不起作用。建议使用 os.path.realpath('./') 或 os.getcwd()。这里最好的分析器:stackoverflow.com/questions/2632199/…
    • @Neon22 可能会满足一些需求,但我觉得应该注意的是,这些东西根本不一样——文件可以在工作目录之外。
    • @Moberg 将realpathdirname 反转时,路径通常相同,但当文件(或其目录)实际上是符号链接时,路径会有所不同。
    • 收到错误NameError: name '__file__' is not defined。如何解决?
    【解决方案2】:

    Current working directory:os.getcwd()

    __file__ attribute 可以帮助您找出您正在执行的文件所在的位置。这篇 Stack Overflow 帖子解释了一切:How do I get the path of the current executed file in Python?

    【讨论】:

      【解决方案3】:

      您可能会发现这是有用的参考:

      import os
      
      print("Path at terminal when executing this file")
      print(os.getcwd() + "\n")
      
      print("This file path, relative to os.getcwd()")
      print(__file__ + "\n")
      
      print("This file full path (following symlinks)")
      full_path = os.path.realpath(__file__)
      print(full_path + "\n")
      
      print("This file directory and name")
      path, filename = os.path.split(full_path)
      print(path + ' --> ' + filename + "\n")
      
      print("This file directory only")
      print(os.path.dirname(full_path))
      

      【讨论】:

      • __file__ 在这里表示什么?它对我不起作用。
      • __file__ 是模块对象的一个​​属性。您需要在 Python 文件中运行代码,而不是在 REPL 上。
      【解决方案4】:

      pathlib 模块 introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths) 让路径相关的体验变得更好。

      pwd
      
      /home/skovorodkin/stack
      
      tree
      
      .
      └── scripts
          ├── 1.py
          └── 2.py
      

      为了获取当前工作目录,使用Path.cwd():

      from pathlib import Path
      
      print(Path.cwd())  # /home/skovorodkin/stack
      

      要获取脚本文件的绝对路径,请使用Path.resolve() 方法:

      print(Path(__file__).resolve())  # /home/skovorodkin/stack/scripts/1.py
      

      并且要获取你的脚本所在目录的路径,访问.parent(建议在.parent之前调用.resolve()):

      print(Path(__file__).resolve().parent)  # /home/skovorodkin/stack/scripts
      

      请记住,__file__ 在某些情况下并不可靠:How do I get the path of the current executed file in Python?


      请注意,Path.cwd()Path.resolve() 和其他 Path 方法返回路径对象(在我的情况下为 PosixPath),而不是字符串。在 Python 3.4 和 3.5 中造成了一些痛苦,因为 open 内置函数只能与字符串或字节对象一起使用,并且不支持 Path 对象,因此您必须将 Path 对象转换为字符串或使用Path.open() 方法,但后一个选项需要您更改旧代码:

      文件scripts/2.py

      from pathlib import Path
      
      p = Path(__file__).resolve()
      
      with p.open() as f: pass
      with open(str(p)) as f: pass
      with open(p) as f: pass
      
      print('OK')
      

      输出

      python3.5 scripts/2.py
      
      Traceback (most recent call last):
        File "scripts/2.py", line 11, in <module>
          with open(p) as f:
      TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
      

      如您所见,open(p) 不适用于 Python 3.5。

      PEP 519 — Adding a file system path protocol,在 Python 3.6 中实现,向 open 函数添加了对 PathLike 对象的支持,因此现在您可以将 Path 对象直接传递给 open 函数:

      python3.6 scripts/2.py
      
      OK
      

      【讨论】:

      • 另请注意,这些方法是可链接的,因此如果需要,您可以使用 app_path = Path(__file__).resolve().parent.parent.parent../../../ 平行。
      • 哪个系统有名为“python3.5”和“python3.6”的可执行文件(或等效文件)? Ubuntu Ubuntu MATE 20.04(Focal Fossa)没有(至少默认情况下没有)。它有名为“python3”和“python2”的可执行文件(但不是“python”——这会导致some things to break
      • @PeterMortensen,感谢您的更正。我不记得当时我是否真的有python3.x 符号链接。也许我认为它会使 sn-ps 对读者更清楚一点。
      【解决方案5】:
      1. 获取当前目录完整路径

        >>import os
        >>print os.getcwd()
        

        输出:“C:\Users\admin\myfolder”

      2. 单独获取当前目录文件夹名称

        >>import os
        >>str1=os.getcwd()
        >>str2=str1.split('\\')
        >>n=len(str2)
        >>print str2[n-1]
        

        输出:“我的文件夹”

      【讨论】:

      • 我认为最好在一行中完成:os.getcwd().split('\\')[-1]
      • 最好使用 os.sep 而不是 Windows 的硬编码:os.getcwd().split(os.sep)[-1]
      • 这种方法的问题在于,如果您从不同的目录执行脚本,您将得到该目录的名称而不是脚本的名称,这可能不是您想要的。
      • 对,你的文件所在的当前目录可能不是你的 CWD
      【解决方案6】:

      Pathlib可以通过这种方式获取包含当前脚本的目录:

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

      【讨论】:

      • 我喜欢这个解决方案。但是可能会导致一些 Python 2.X 问题。
      • 对于 python 3.3 及更早版本必须安装 pathlib
      • @Kimmo 您应该使用 Python 2 代码的唯一原因是将其转换为 Python 3。
      • @kagnirick 同意,但仍有人不同意。我使用 Python 3.6 使用格式化字符串文字 (PEP 498) 编写所有新内容,这样就不会有人将它们推送到 Python2。
      • 另请注意,这些方法是可链接的,因此如果需要,您可以将app_path = Path(__file__).resolve().parent.parent.parent../../../ 并行使用。
      【解决方案7】:

      如果您正在尝试查找当前所在文件的当前目录:

      操作系统不可知的方式:

      dirname, filename = os.path.split(os.path.abspath(__file__))
      

      【讨论】:

        【解决方案8】:

        如果您使用的是 Python 3.4,则有全新的更高级别的 pathlib 模块,它允许您方便地调用 pathlib.Path.cwd() 来获取代表当前工作目录的 Path 对象,以及许多其他新的功能。

        有关此新 API 的更多信息,请访问 here

        【讨论】:

        【解决方案9】:

        获取当前目录完整路径:

        os.path.realpath('.')
        

        【讨论】:

        • 这个在 jupyter iPython notebook 中工作('__file__' 和 getcwd 不会)
        • 仍然有效。感谢未来的@OliverZendel!
        • 我正在使用 Jupyter Notebook 远程工作:os.getcwd() 和 `os.path.realpath('.') 返回完全相同的字符串路径。
        • @Leevo:点存在?
        【解决方案10】:

        #1 的答案:

        如果你想要当前目录,这样做:

        import os
        os.getcwd()
        

        如果您只需要任何文件夹名称并且您有该文件夹的路径,请执行以下操作:

        def get_folder_name(folder):
            '''
            Returns the folder name, given a full folder path
            '''
            return folder.split(os.sep)[-1]
        

        回答 #2:

        import os
        print os.path.abspath(__file__)
        

        【讨论】:

          【解决方案11】:

          我认为查找当前执行上下文名称的最简洁方法是:

          current_folder_path, current_folder_name = os.path.split(os.getcwd())
          

          【讨论】:

            【解决方案12】:

            如果您正在搜索当前执行脚本的位置,您可以使用sys.argv[0] 获取完整路径。

            【讨论】:

            • 这是错误的。 sys.argv[0] 不需要包含执行脚本的完整路径。
            【解决方案13】:

            对于问题 1,请使用 os.getcwd() # Get working directoryos.chdir(r'D:\Steam\steamapps\common') # Set working directory


            我建议在问题 2 中使用sys.argv[0],因为sys.argv 是不可变的,因此始终返回当前文件(模块对象路径)并且不受os.chdir() 的影响。你也可以这样做:

            import os
            this_py_file = os.path.realpath(__file__)
            
            # vvv Below comes your code vvv #
            

            但是当由 PyInstaller 编译时,sn-p 和 sys.argv[0] 将不起作用或会奇怪地工作,因为魔法属性未在 __main__ 级别设置,而 sys.argv[0] 是调用可执行文件的方式(这意味着它会受到工作目录的影响)。

            【讨论】:

              猜你喜欢
              • 2017-01-07
              • 1970-01-01
              • 2019-06-14
              • 2018-06-25
              • 2019-06-17
              • 2014-03-29
              相关资源
              最近更新 更多