• 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
  • 相关阅读:
    转 Android之Broadcast, BroadcastReceiver(广播)
    Android之“==”与equals区别
    Android之notificaction使用
    android service 学习
    Android之Menu.add()
    (转)Android生命周期
    Partial Method in VB.NET
    如何侦测机器上装的.net framework的版本
    Powersehll: match ,cmatch,imatch命令
    Office Tip(1) : Split the Screen
  • 原文地址:https://www.cnblogs.com/liuyi1804/p/14803345.html
Copyright © 2020-2023  润新知