如何确定:

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


当前回答

获取当前目录完整路径>>导入操作系统>>打印os.getcwd()输出:“C:\Users\admin\myfolder”仅获取当前目录文件夹名称>>导入操作系统>>str1=os.getcwd()>>str2=str1.split('\\')>>n=长度(str2)>>打印str2[n-1]输出:“myfolder”

其他回答

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

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的更多信息,请参阅此处。

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

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

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

操作系统不可知的方式:

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

获取当前目录完整路径>>导入操作系统>>打印os.getcwd()输出:“C:\Users\admin\myfolder”仅获取当前目录文件夹名称>>导入操作系统>>str1=os.getcwd()>>str2=str1.split('\\')>>n=长度(str2)>>打印str2[n-1]输出:“myfolder”