如何确定:

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


当前回答

要获取当前目录的完整路径,请执行以下操作:

os.path.realpath('.')

其他回答

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

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

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

操作系统不可知的方式:

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

对于问题1,使用os.getcwd()#获取工作目录和os.chdir(r'D:\SSteam\stamapps\common')#设置工作目录


我建议对问题2使用sys.argv[0],因为sys.argv是不可变的,因此始终返回当前文件(模块对象路径),不受os.chdir()的影响。也可以这样做:

import os
this_py_file = os.path.realpath(__file__)

# vvv Below comes your code vvv #

但当PyInstaller编译时,该代码段和sys.argv[0]将无法工作或工作异常,因为魔法财产没有在__main__level中设置,而sys.argv[0]是调用可执行文件的方式(这意味着它会受到工作目录的影响)。

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

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

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