如何确定:
当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?
如何确定:
当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?
当前回答
如果要搜索当前执行的脚本的位置,可以使用sys.argv[0]获取完整路径。
其他回答
可以通过以下方式使用Pathlib来获取包含当前脚本的目录:
import pathlib
filepath = pathlib.Path(__file__).resolve().parent
如果要搜索当前执行的脚本的位置,可以使用sys.argv[0]获取完整路径。
您可能会发现这是一个有用的参考:
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())
要获取当前目录的完整路径,请执行以下操作:
os.path.realpath('.')