如何确定:

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


当前回答

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

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

其他回答

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

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

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

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

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

有关此新API的更多信息,请参阅此处。

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

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