python 获取文件路径相关
1、只获得路径的最后一部分
import os os.path.basename('C:\\Users\\Administrator\\Desktop') Out[81]: 'Desktop' os.path.basename('C:\\Users\\Administrator\\Desktop\\a.txt') Out[82]: 'a.txt'
2、对目录结构的操作
import os print '***获取当前目录***' print os.getcwd() print os.path.abspath(os.path.dirname(__file__)) print '***获取上级目录***' print os.path.abspath(os.path.dirname(os.path.dirname(__file__))) print os.path.abspath(os.path.dirname(os.getcwd())) print os.path.abspath(os.path.join(os.getcwd(), "..")) print '***获取上上级目录***' print os.path.abspath(os.path.join(os.getcwd(), "../.."))
结果:
***获取当前目录*** /workspace/demo/folder/test /workspace/demo/folder/test ***获取上级目录*** /workspace/demo/folder /workspace/demo/folder /workspace/demo/folder ***获取上上级目录*** /workspace/demo
参考:https://blog.csdn.net/leorx01/article/details/71141643