How to get full path of current file's directory in Python?
我想获取当前文件的目录路径。我试过:
1 2 | >>> os.path.abspath(__file__) 'C:\\python27\\test.py' |
但是如何检索目录的路径?例如:
1 | 'C:\\python27\' |
如果您是指正在运行的脚本的目录:
1 2 | import os os.path.dirname(os.path.abspath(__file__)) |
如果您指的是当前工作目录:
1 2 | import os os.getcwd() |
注意,在
另外,请注意,如果您正在交互运行或已从文件以外的其他文件(例如:数据库或联机资源)加载代码,则可能不会设置
在Python 3中:
1 2 3 4 | from pathlib import Path mypath = Path().absolute() print(mypath) |
Pathlib文档
1 2 | import os print os.path.dirname(__file__) |
您可以轻松使用
1 2 | import os os.chdir(os.path.dirname(os.getcwd())) |
在python 3.x i中:
1 2 3 | from pathlib import Path path = Path(__file__).parent.absolute() |
说明:
Path(__file__) 是当前文件的路径。.parent 提供了文件所在的目录。.absolute() 为您提供了通往它的完全绝对路径。
使用
python中有用的路径属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from pathlib import Path #Returns the path of the directory, where your script file is placed mypath = Path().absolute() print('Absolute path : {}'.format(mypath)) #if you want to go to any other file inside the subdirectories of the directory path got from above method filePath = mypath/'data'/'fuel_econ.csv' print('File path : {}'.format(filePath)) #To check if file present in that directory or Not isfileExist = filePath.exists() print('isfileExist : {}'.format(isfileExist)) #To check if the path is a directory or a File isadirectory = filePath.is_dir() print('isadirectory : {}'.format(isadirectory)) #To get the extension of the file fileExtension = mypath/'data'/'fuel_econ.csv' print('File extension : {}'.format(filePath.suffix)) |
输出:绝对路径是放置python文件的路径
绝对路径:d:studymachine learningjupitor notebookjupytornotebook test2udacity_scriptsmatplotlib和seaborn part2
文件路径:d:studymachine learningjupitor notebookjupytornotebook test2udacity_scriptsmatplotlib and seaborn part2datafuel_econ.csv
isfileexist:真
isaDirectory:错误
文件扩展名:.csv
系统:MACOS
版本:python 3.6 w/anaconda
rootpath = os.getcwd()
os.chdir(rootpath)
我在CGI中的IIS下运行python时使用了一个函数,以获取当前文件夹:
1 2 3 4 | import os def getLocalFolder(): path=str(os.path.dirname(os.path.abspath(__file__))).split('\') return path[len(path)-1] |
要保持跨平台(MacOS/Windows/Linux)的迁移一致性,请尝试:
1 | path = r'%s' % os.getcwd().replace('\','/') |
1 2 3 4 5 | from IPython.terminal.embed import InteractiveShellEmbed ip_shell = InteractiveShellEmbed() present_working_directory = ip_shell.magic("%pwd") |
在IPython Jupyter笔记本电脑上,
1 | present_working_directory = %pwd |
1 2 3 4 5 6 7 | ## IMPORT MODULES import os ## CALCULATE FILEPATH VARIABLE filepath = os.path.abspath('') ## ~ os.getcwd() ## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS.. ## ..OR DIFFERENT IN SOME CIRCUMSTANCES |