赞
踩
我们经常会与文件和目录打交道,对于这些操作python提供了一个os模块,里面包含了很多操作文件和目录的函数。想要知道有哪些方法,我们可以运行下面的语句,就可以在屏幕上输出os模块的所有信息:
- import os
- help(os)
如果你对linux基本操作了解的话,下面的一些os方法应该会很熟悉的,因为基本和linux下的操作方法相同。下面举几个常用的:
- import os
-
- Base1 = os.path.dirname(__file__)
- Base2 = os.path.abspath(__file__)
- BASE_DIR1 = os.path.dirname(os.path.dirname(__file__))
- BASE_DIR2 = os.path.dirname(os.path.abspath(__file__))
- join_dir = os.path.join(BASE_DIR1,'templates')
- join_dir2 = os.path.join(BASE_DIR1, '..')
-
- print "__file__: ",__file__
- print "os.path.dirname: ",Base1
- print "os.path.abspath: ",Base2
- print "double dirname: ",BASE_DIR1
- print "dirname and abspath: ",BASE_DIR2
- print "join_dir: ",join_dir
-
- #__file__: /Users/admin/PycharmProjects/test/dirTest.py
- #os.path.dirname: /Users/admin/PycharmProjects/test
- #os.path.abspath: /Users/admin/PycharmProjects/test/dirTest.py
- #double dirname: /Users/admin/PycharmProjects
- #dirname and abspath: /Users/admin/PycharmProjects/test
- #join_dir: /Users/admin/PycharmProjects/templates

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。