如何确定:

当前目录(运行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))

其他回答

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

要获取Python文件所在目录的完整路径,请在该文件中写入以下内容:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

(请注意,如果您已经使用os.chdir()更改了当前工作目录,则上面的咒语将不起作用,因为__file__常量的值是相对于当前工作目录的,并且不会被os.chdir()调用更改。)


要获取当前工作目录,请使用

import os
cwd = os.getcwd()

上述模块、常数和函数的文档参考:

os和os.path模块。__file__常量os.path.realpath(路径)(返回“指定文件名的规范路径,消除路径中遇到的任何符号链接”)os.path.dirname(路径)(返回“路径名路径的目录名”)os.getcwd()(返回“表示当前工作目录的字符串”)os.chdir(路径)(“将当前工作目录更改为路径”)

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

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

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