如何确定:
当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?
如何确定:
当前目录(运行Python脚本时我在shell中的位置),以及我正在执行的Python文件在哪里?
当前回答
答案#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()
__file__属性可以帮助您找到正在执行的文件的位置。这篇StackOverflow文章解释了一切:如何在Python中获取当前执行文件的路径?
要获取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(路径)(“将当前工作目录更改为路径”)
如果您使用的是Python3.4,有一个全新的高级pathlib模块,它允许您方便地调用pathlib.Path.cwd()以获取表示当前工作目录的Path对象,以及许多其他新功能。
有关此新API的更多信息,请参阅此处。
您可能会发现这是一个有用的参考:
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__))