如何确定:

当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?


当前回答

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

操作系统不可知的方式:

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

其他回答

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

操作系统不可知的方式:

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

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

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

答案#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__)

可以通过以下方式使用Pathlib来获取包含当前脚本的目录:

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

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