首页 文章

查找当前目录和文件的目录[重复]

提问于
浏览
1642

这个问题在这里已有答案:

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

  • 当前目录(当我运行Python脚本时我在终端中的位置),以及

  • 我正在执行的文件是哪个?

15 回答

  • 278

    如果您要查找当前所在文件的当前目录:

    OS不可知的方式:

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

    为了查看以下脚本的当前工作目录类型:

    import os
    current_working_directory = os.getcwd()
    
  • 25

    问题1使用 os.getcwd() # get working diros.chdir(r'D:\Steam\steamapps\common') # set working dir


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

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

    但是,当PyInstaller编译时,该片段和 sys.argv[0] 将无法正常工作或工作,因为魔法属性未在 __main__ 级别设置, sys.argv[0] 是您调用exe的方式(意味着它受工作目录的影响) .

  • 47

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

  • 2529

    在Python 3.4(PEP 428 — The pathlib module — object-oriented filesystem paths)中,pathlib module,introduced使路径相关的体验变得更好 .

    $ 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()方法,但后者选项要求你改变旧代码:

    $ cat 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中实现,将PathLike对象的支持添加到open函数,所以现在可以直接将 Path 对象传递给 open 函数:

    $ python3.6 scripts/2.py
    OK
    
  • 26

    要获取包含Python文件的目录的完整路径,请在该文件中写入:

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

    (请注意,上面的咒语已经't work if you'已使用 os.chdir() 来更改当前的工作目录,因为 __file__ 常量的值是相对于当前工作目录的,并且不会被 os.chdir() 调用更改 . )


    要使用当前工作目录

    import os
    cwd = os.getcwd()
    

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

  • 26

    派对有点晚了,但我认为找到当前执行上下文名称的最简洁方法是

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

    当前工作目录:os.getcwd()

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

  • 17

    可以使用Pathlib来获取包含当前脚本的目录:

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

    Answer to #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]
    

    Answer to #2:

    import os
    print os.path.abspath(__file__)
    
  • 7

    1.获取当前目录的完整路径

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

    o / p:“C:\ Users \ admin \ myfolder”

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

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

    O / P: “MyFolder文件”

  • 9

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

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

  • 5

    要获取当前目录的完整路径:

    os.path.realpath(' . ')

  • 33

    在python中获取工作目录 . 您可以使用以下代码:

    import os
    cwd = os.getcwd() #to get current working directory
    print(cwd)
    
  • 30

    您可能会发现这有用作为参考:

    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))
    

相关问题