python3 获取当前路径及os.path.dirname的使用

方法一:html

import sys,os
os.getcwd()#而后就能够看见结果了

方法二:python

import os
os.path.dirname(os.path.realpath('__file__'))#注意:添加单引号

python中的os.path.dirname(__file__)的使用post

(1)当"print os.path.dirname(__file__)"所在脚本是以完整路径被运行的, 那么将输出该脚本所在的完整路径,好比:url

             python d:/pythonSrc/test/test.pyspa

             那么将输出 d:/pythonSrc/test.net

(2)当"print os.path.dirname(__file__)"所在脚本是以相对路径被运行的, 那么将输出空目录,好比:code

             python test.pyhtm

             那么将输出空字符串blog

python中的os.path.dirname(path)字符串

语法:os.path.dirname(path) 
功能:去掉文件名,返回目录 
如:

print(os.path.dirname('W:\Python_File\juan之购物车.py'))
#结果
#W:\Python_File
print(os.path.dirname('W:\Python_File'))
#结果
#W:\

参考博客:

python中的os.path.dirname与os.path.dirname(__file__)的用法

解决NameError: global name '__file__' is not defined

相关文章
相关标签/搜索