how do you get the current local directory in python

This question already has an answer here:

  • Find current directory and file's directory [duplicate] 15 answers

  • 我会使用basename

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

    Try these

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

    Taken from here: Find current directory and file's directory

    Edit: here is another from that question

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

    os.path contains lots of useful path manipulation functions. I think you're looking for os.path.basename . It is preferable to use os.path because your program will be cross-platform: currently, your solution would not work for Windows. The cross-platform way of getting the name of the directory you're in would be

    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/54708.html

    上一篇: 获取脚本目录名称

    下一篇: 你如何在Python中获取当前的本地目录