zoukankan      html  css  js  c++  java
  • python中pathlib库的应用(pathlib.Path)

    相较于os.path的嵌套操作,pathlib似乎来得更优雅了!

    对比输出下!

     1 import os.path
     2 from pathlib  import Path
     3 
     4 # 获取上层目录
     5 base_dir = os.path.dirname(os.path.dirname(os.path.absname(__file__)))
     6 print("base_dir : " + base_dir)
     7 
     8 file_dir1 = os.path.dirname(getcwd())
     9 print(file_dir1)
    10 
    11 file_dir1_1 = Path.cwd().parent
    12 print(file_dir1_1)
    13 
    14 # 获取当前文件路径
    15 file_dir2 = Path.cwd()
    16 print(dile_dir2)
    17 
    18 file_dir2_1 = os.getcwd()
    19 print(file_dir2_1)
    20 
    21 # 拼接目录
    22 paths = os.path.jion(os.path.dirname(os.getcwd()), 'logs', 'logs.log')
    23 print(paths)
    24 
    25 paths = ['losgs', 'logs.log']
    26 paths1_1 = Path.cwd().parent.jionpath(*paths1)
    27 print(paths1_1)
    28 
    29 paths1_2 = os.path.dirname(os.path.absname('.')) + '/screenshots/'
    30 print(paths1_2)
    31 
    32 paths1_3 = Paht.cwd().parent / 'screentshots'
    33 print(paths1_3)

     os模块与pathlib中的方法对比

     1 os and os.path    pathlib
     2 os.path.abspath()    Path.resolve()
     3 os.chmod()    Path.chmod()
     4 os.mkdir()    Path.mkdir()
     5 os.rename()    Path.rename()
     6 os.replace()    Path.replace()
     7 os.rmdir()    Path.rmdir()
     8 os.remove(), os.unlink()    Path.unlink()
     9 os.getcwd()    Path.cwd()
    10 os.path.exists()    Path.exists()
    11 os.path.expanduser()    Path.expanduser() and Path.home()
    12 os.path.isdir()    Path.is_dir()
    13 os.path.isfile()    Path.is_file()
    14 os.path.islink()    Path.is_symlink()
    15 os.stat() Path.stat(),    Path.owner(), Path.group()
    16 os.path.isabs()    PurePath.is_absolute()
    17 os.path.join()    PurePath.joinpath()
    18 os.path.basename()    PurePath.name
    19 os.path.dirname()    PurePath.parent
    20 os.path.samefile()    Path.samefile()
    21 os.path.splitext()    PurePath.suffix
  • 相关阅读:
    域名系统
    DNS域名解析过程
    服务器常用的状态码
    重绘与重排及它的性能优化
    console.time和console.timeEnd用法
    用CSS开启硬件加速来提高网站性能
    公钥和私钥
    svn conflict 冲突解决
    svn分支开发与主干合并(branch & merge)
    源生js惯性滚动与回弹效果
  • 原文地址:https://www.cnblogs.com/liuyi1804/p/14803345.html
Copyright © 2011-2022 走看看