python中os.path模块的使用

1、os.path.dirname(file) #指的是 当前文件所在目录,即settings.py在哪个文件夹里。

用print os.path.dirname(file) #输出结果: D:\MyPython\LearnDJ\src\LearnDJ\book

2、os.path.abspath(file) #指的是 当前文件的绝对路径,包括文件名。

用print os.path.abspath(file) #输出结果 : D:\MyPython\LearnDJ\src\LearnDJ\book\settings.py

3、os.path.dirname(os.path.dirname(file)) #指的是 当前文件所在目录的所在目录,即上一层文件夹。

用print os.path.dirname(os.path.dirname(file)) #输出结果 : D:\MyPython\LearnDJ\src\LearnDJ

4、 os.path.join #在原有路径的后面加上新的相对路径。格式为os.path.join(BASE_DIR, addpath)
  需要注意的是:如果附加的路径由多级目录,addpath不能采用“\dir1\dir2\file.txt”这种形式,而要采用os.path.join(BASE_DIR, dir1,dir2,file)这种形式。

path = r’E:\prj\notebook\django\channelsTest’
print(path)
pathfull = os.path.join(path,r’entry’,r’test’,r’test.log’)
print(pathfull)
输出为:
E:\prj\notebook\django\channelsTest
E:\prj\notebook\django\channelsTest\entry\test\test.log

参考文章

全面解析Django的模板路径设置templates(settings.py)
http://blog.csdn.net/komtao520/article/details/52447608

猜你喜欢

转载自blog.csdn.net/xys430381_1/article/details/78404832