python目录的操作

python中涉及到文件路径的paths操作需要用到模块,网上许多关于os module的教程,如教程1教程2

本文主要对一些常用的目录操作进行简单小结

获取当前python/ipynb脚本的工作路径

import os

pwd = os.getcwd()
print 'the value of pwd:',pwd
print 'the type of pwd',type(pwd)

结果如下:

the value of pwd: /root/workspace/tingting/ImageProcessing
the type of pwd

获取当前工作目录的上一级目录

import os
pwd = os.getcwd()
print 'the present working directory is: ',pwd
pwd_up = os.path.abspath(os.path.join(pwd,os.path.pardir))
print 'the directory folder of the present working directory is: ',pwd_up

结果如下:

the present working directory is: /root/workspace/tingting/ImageProcessing
the directory folder of the present working directory is: /root/workspace/tingting

可以看到,字符类型变量pwd存储的是当前运行的python/ipynb脚本文件的工作目录,而
pwd_up存储的是其上一级目录

发表评论