如何获得当前Python脚本文件的文件夹路径
我们在Python 3基础教程中介绍了文件和文件夹操作,在本贴士中我们来介绍下如何得到当前Python脚本文件的相对和绝对路径。
获得Python工作目录
os.getcwd()
函数返回了当前Python工作目录,如果你是在Python IDLE
中运行该命令的话,返回结果就是Python IDLE
的路径。
Python中获得该执行文件的目录
脚本文件的路径可以在全局命名空间中找到,它的变量名称是__file__
。该变量是相对于Python工作目录的相对路径。
我们用示例代码来实际操作下刚才介绍的知识。
import os
wd = os.getcwd()
print("working directory is ", wd)
filePath = __file__
print("This script file path is ", filePath)
absFilePath = os.path.abspath(__file__)
print("This script absolute path is ", absFilePath)
path, filename = os.path.split(absFilePath)
print("Script file path is {}, filename is {}".format(path, filename))
absFilePath = os.path.abspath(__file__)
os.path.abspath(__file__)
函数的结果是给定相对路径的绝对路径。
path, filename = os.path.split(absFilePath)
os.path.split()
函数返回了两个结果,一个是输入文件名的纯路径名,另一个是纯文件名。