IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]8.1 pathlib--面向对象设计的文件系统路径

    caimouse发表于 2016-02-28 09:11:10
    love 0

    8. 文件和目录的使用库

    本库主要提供了处理磁盘文件和目录相关功能。比如有些模块读取文件属性,或者使用一个通用方式操作文件路径,或者创建一个临时文件。

    8.1 pathlib--面向对象设计的文件系统路径

    本模块主要提供了不同操作系统下的文件系统路径的操作方式。路径类分为纯路径操作无I/O操作的类和有I/O操作相关的类。整个路径的继承关系图如下:

    如果从来没有使用过本模块里的类,以及也不清楚使用那一个类时,可以先使用Path类,它提供了一些协助操作路径的类。

    纯路径操作在某种情况之下,也是有特殊的需要:

    1. 比如在Unix系统下操作Windows路径,这时在Unix下面没办法使用 WindowsPath类,就可以使用PureWindowsPath类。

    2. 比如只想操作路径,但不访问OS的路径相关功能。

    8.1.1 基本使用

    导入主要使用的类和显示当前子目录:

    #python 3.4

    from pathlib import Path

     

    p = Path('.')

    r = [x for x in p.iterdir() if x.is_dir()]

    print(r)

    结果输出如下:

    [WindowsPath('micropython-master')]

     

    查找一个目录下的文件,判断路径是否为目录,判断文件是否存在

    例子:

    #python 3.4

    from pathlib import Path

     

    p = Path('F:\\temp\\py')

    print(list(p.glob('**/*.py')))

    q = p / 'cal_1.py'

    print(q, q.resolve(), q.exists(), q.is_dir())

    结果输出如下:

    [WindowsPath('F:/temp/py/bisect1.py'), WindowsPath('F:/temp/py/cal_1.py'), WindowsPath('F:/temp/py/chainmap1.py'), WindowsPath('F:/temp/py/chainmap2.py'), WindowsPath('F:/temp/py/closescreen.py'), WindowsPath('F:/temp/py/codecs1.py'), WindowsPath('F:/temp/py/complex1.py'), WindowsPath('F:/temp/py/copy1.py'), WindowsPath('F:/temp/py/datetimetz.py'), WindowsPath('F:/temp/py/dec1.py'), WindowsPath('F:/temp/py/difflib1.py'), WindowsPath('F:/temp/py/difflib2.py'), WindowsPath('F:/temp/py/difflib3.py'), WindowsPath('F:/temp/py/difflib4.py'), WindowsPath('F:/temp/py/difflib5.py')]

    F:\temp\py\cal_1.py F:\temp\py\cal_1.py True False



    蔡军生 QQ:9073204  深圳



沪ICP备19023445号-2号
友情链接