如何确定:
当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?
如何确定:
当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?
当前回答
当前工作目录:os.getcwd()
__file__属性可以帮助您找到正在执行的文件的位置。这篇StackOverflow文章解释了一切:如何在Python中获取当前执行文件的路径?
其他回答
当前工作目录:os.getcwd()
__file__属性可以帮助您找到正在执行的文件的位置。这篇StackOverflow文章解释了一切:如何在Python中获取当前执行文件的路径?
我认为找到当前执行上下文名称的最简洁方法是:
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))
答案#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__)
获取当前目录完整路径>>导入操作系统>>打印os.getcwd()输出:“C:\Users\admin\myfolder”仅获取当前目录文件夹名称>>导入操作系统>>str1=os.getcwd()>>str2=str1.split('\\')>>n=长度(str2)>>打印str2[n-1]输出:“myfolder”