你如何在Python中获取当前的本地目录

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

  • 查找当前目录和文件的目录[复制] 15个答案

  • 我会使用basename

    import os
    
    path = os.getcwd()
    print(os.path.basename(path))
    

    试试这些

    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, file = os.path.split(full_path)
    print(path + ' --> ' + file + "n")
    
    print("This file directory only")
    print(os.path.dirname(full_path))
    

    采取从这里:查找当前目录和文件的目录

    编辑:这是另一个从这个问题

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

    os.path包含大量有用的路径操作函数。 我想你正在寻找os.path.basename 。 最好使用os.path因为你的程序是跨平台的:目前,你的解决方案不适用于Windows。 获取您所在目录的名称的跨平台方式是

    import os
    cwd = os.getcwd()
    
    # use os.path.basename instead of your own function!
    print(os.path.basename(cwd))
    
    # Evaluates to True if you have Unix-y path separators: try it out!
    os.path.basename(cwd) == cwd.split('/')[-1] 
    >>> True
    
    链接地址: http://www.djcxy.com/p/54707.html

    上一篇: how do you get the current local directory in python

    下一篇: How to indicate the current directory of the script not me?