os处理上下级目录

首先导入os模块和其中的path模块

from os import path
import os

文件结构

7415868-5e53e24bd120bafa.png
image.png

获取当前文件所在目录

now = path.dirname(__file__)

file 为当前文件, 等同于:

now = path.dirname('.')

获得父级目录

now_parent = os.path.dirname(now)  # 获得now的文件所在的目录,即父级目录
parent_path = os.path.dirname(parent_path)  ##now_parent的父级目录

返回now文件所在路径

    abspath = path.abspath(d)  # 返回文件所在目录规范的绝对路径

运行结果

#*-执行:-*
    print("文件所在路径:", now)
    print("now_path:", now_path)
    print("parent_path:", parent_path)
    print("文件完整路径", abspath)

#*-结果:-*

 F:\ServerveManager\python\python.exe "F:/ServerveManager/Pycharm/PyCharm 2018.2.2/files/python_test/test_11_06/test1.py"
文件所在路径: F:/ServerveManager/Pycharm/PyCharm 2018.2.2/files/python_test/test_11_06
now_path: F:/ServerveManager/Pycharm/PyCharm 2018.2.2/files/python_test
parent_path: F:/ServerveManager/Pycharm/PyCharm 2018.2.2/files
文件完整路径 F:\ServerveManager\Pycharm\PyCharm 2018.2.2\files\python_test\test_11_06

猜你喜欢

转载自blog.csdn.net/weixin_33834628/article/details/87230554
今日推荐