zoukankan      html  css  js  c++  java
  • Python标准库之pathlib

    目录操作

    导入主要的类

    from pathlib import Path

    初始化

    >>> p = Path()  # 当前目录
    >>> p = Path('a','b','c/d')  # 当前目录下的a/b/c/d
    >>> p = Path('/etc')  # 根下的etc目录
    路径拼接和分解

    拼接操作符:/

    Path对象 / Path对象

    Path对象 / 字符串

    字符串 / Path对象

    分解

    parts属性,可以返回路径中的每一部分

    joinpath

    joinpath(*other)连接多个字符串到Path对象中

    >>> p = Path()
    >>> p
    WindowsPath('.')
    >>> p = p / 'a'
    >>> p
    WindowsPath('a')
    >>> p1 = 'b' / p
    >>> p1
    WindowsPath('b/a')
    >>> p2 = Path('c')
    >>> p3 = p2 / p1
    >>> p3
    WindowsPath('c/b/a')
    >>> p3.parts
    ('c', 'b', 'a')
    >>> p3.joinpath('C:', 'Users', 'Administrator', 'Desktop')
    WindowsPath('C:Users/Administrator/Desktop')
    

    获取路径

    获取路径字符串

    获取路径字符串的bytes

    >>> p = Path('C:/Users/Administrator/Desktop/')
    >>> print(str(p), bytes(p))
    C:\Users\Administrator\Desktop b'C:\\Users\\Administrator\\Desktop'
    
    父目录

    parent属性 目录的逻辑父目录

    parents属性 父目录序列,索引0是直接的父目录,索引越大越接近根

    >>> p = Path('C:/Users/Administrator/Desktop/')
    >>> p.parent
    WindowsPath('C:/Users/Administrator')
    >>> p.parent.parent
    WindowsPath('C:/Users')
    >>> for x in p.parents: print(x)
    C:\Users\Administrator
    C:\Users
    C:\
    
    文件名

    name 目录的最后一个部分

    suffix 目录中最后一个部分的扩展名

    suffixes 返回多个扩展名列表

    stem 目录最后一个部分,没有后缀

    with_name(name) 替换目录最后一个部分并返回一个新的路径

    with_suffix(suffix) 替换扩展名,返回新的路径,扩展名存在则不变

    >>> p = Path('/hidog/text.tar.gz')
    >>> p.name
    'text.tar.gz'
    >>> p.suffix
    '.gz'
    >>> p.suffixes
    ['.tar', '.gz']
    >>> p.stem
    'text.tar'
    >>> p.with_name('haha.tgz')
    WindowsPath('/hidog/haha.tgz')
    >>> p.with_suffix('.gz')
    WindowsPath('/hidog/text.tar.gz')
    >>> p.with_suffix('.txt')
    WindowsPath('/hidog/text.tar.txt')
    

    cwd()

    返回一个表示当前目录的新路径对象:

    >>> Path.cwd()
    WindowsPath('C:/Users/Administrator/my_practice')
    >>> p = Path()
    >>> p.cwd()
    WindowsPath('C:/Users/Administrator/my_practice')
    

    home()

    返回一个表示当前用户HOME目录的新路径对象:

    >>> Path.home()
    WindowsPath('C:/Users/Administrator')
    
    判断路径的类型

    返回:布尔值

    is_dir() 是否是目录

    is_file() 是否是普通文件

    is_symlink() 是否是软链接

    is_socket() 是否是socket文件

    is_block_device() 是否是块设备

    is_char_device() 是否是字符设备

    is_absolute() 是否是绝对路径

    resolve() 返回一个新的路径,这个新路径就是当前Path对象的绝对路径,如果是软链接则直接被解析

    absolute() 也可以获取绝对路径,但是推荐resolve()

    exists()

    该路径是否指向现有的目录或文件:

    >>> Path('C:/Users/Administrator/Desktop/text.txt').exists()
    True
    

    rmdir() 删除空目录。没有提供判断目录是否为空的方法

    touch(mode=0o666, exist_ok=True) 创建一个文件

    as_uri() 将路径返回成URI(Uniform Resource Identifier,统一资源标识符,是一个用于标识某一互联网资源名称的字符串),例如'file:///etc/passwd'

    mkdir(mode=0o777,parents=False,exist_ok=False) 创建目录

    parents:是否创建父目录,True等同mkdir -p;False时,父目录不存在,则抛出FileNotFoundError

    exist_ok:在3.5版本加入。False时,路径存在,抛出FileExistsError;True时,FileExistsError被忽略

    >>> p = Path('C:/Users/Administrator/Desktop/')
    >>> p = p / 'test' / 'test1'
    >>> p.mkdir(parents=True)  # 在桌面上创建test目录,创建test1目录
    

    iterdir() 迭代当前目录:

    >>> p = Path('C:/Users/Administrator/Desktop/')
    >>> [x for x in p.iterdir()]
    [WindowsPath('C:/Users/Administrator/Desktop/reg.txt'),
    WindowsPath('C:/Users/Administrator/Desktop/新建文件夹'),
    WindowsPath('C:/Users/Administrator/Desktop/Path.pdf'),
    ……
    WindowsPath('C:/Users/Administrator/Desktop/Xshell.lnk')]
    
    通配符

    glob(pattern) 通配给定的模式

    rglob(pattern) 通配给定的模式,递归目录

    返回一个生成器

    >>> p = Path('C:/Users/Administrator/Desktop/')
    >>> list(p.glob('test*'))  # 返回当前目录对象下的以test开头的文件
    [WindowsPath('C:/Users/Administrator/Desktop/test.ini'),
     WindowsPath('C:/Users/Administrator/Desktop/test.py')]
    >>> list(p.glob('**/*.txt'))  # 递归所有目录,返回txt格式的文件,等同rglob
    [WindowsPath('C:/Users/Administrator/Desktop/reg.txt'),
     WindowsPath('C:/Users/Administrator/Desktop/sample.txt'),
     WindowsPath('C:/Users/Administrator/Desktop/text.txt'),
     WindowsPath('C:/Users/Administrator/Desktop/newfolder/新建文本文档.txt'),
     WindowsPath('C:/Users/Administrator/Desktop/newfolder/newfolder1/新建文本文档1.txt')]
    >>> g = p.rglob('*.py')  # 生成器
    >>> next(g)
    WindowsPath('C:/Users/Administrator/Desktop/test.py')
    
    匹配

    match(pattern)

    模式匹配,成功返回True

    >>> p = Path('C:/Users/Administrator/Desktop/text.txt')
    >>> p.match('*.txt')
    True
    >>> Path('C:/Users/Administrator/Desktop/text.txt').match('**/*.txt')
    True
    

    stat() 相当于stat命令

    lstat() 同stat(),但如果是符号链接(软链接),则显示符号链接本身的文件信息

    返回路径的信息,每次调用此方法时都要查看结果:

    >>> p = Path('C:/Users/Administrator/Desktop/text.txt')
    >>> p.stat()
    os.stat_result(st_mode=33206, st_ino=2533274790402060, st_dev=48152560, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1524986835, st_mtime=1525066548, st_ctime=1524986835)
    >>> p.stat().st_size  # 文件大小12字节
    12
    >>> p.lstat()
    os.stat_result(st_mode=33206, st_ino=2533274790402060, st_dev=48152560, st_nlink=1, st_uid=0, st_gid=0, st_size=12, st_atime=1524986835, st_mtime=1525066548, st_ctime=1524986835)
    

    文件操作

    open(mode='r', bufferiong=-1, encoding=None, errors=None, newline=None)

    使用方法类似内建函数open。返回一个文件对象

    >>> p = Path('C:/Users/Administrator/Desktop/text.txt')
    >>> with p.open(encoding='utf-8') as f: print(f.readline())  # win下‘GBK’,需要转码
    测试一下
    

    read_bytes()

    以'rb'读取路径对应文件,并返回二进制流

    Path.write_bytes(data)

    以'wb'方式写入数据到路径对应文件

    >>> p = Path('C:/Users/Administrator/Desktop/text.txt')
    >>> p.write_bytes(b'Binary file contents')
    20
    >>> p.read_bytes()
    b'Binary file contents'
    

    read_text(encoding=None, errors=None)

    以'rt'方式读取路径对应文件,返回文本

    write_text(data, encoding=None, errors=None)

    以'wt'方式写入字符串到路径对应文件

    >>> p = Path('C:/Users/Administrator/Desktop/text.txt')
    >>> p.write_text('Text file contents')
    18
    >>> p.read_text()
    'Text file contents'
    
  • 相关阅读:
    小程序面试题及答案
    Git常用指令
    《剑指offer》面试题23 从上往下打印二叉树 Java版
    《剑指offer》面试题22 栈的压入、弹出序列 Java版
    《剑指offer》面试题21 包含min函数的栈 Java版
    《剑指offer》面试题20 顺时针打印矩阵 Java版
    《剑指offer》面试题19 二叉树的镜像 Java版
    《剑指offer》面试题18 树的子结构 Java版
    《剑指offer》面试题17 合并两个排序的链表 Java版
    《剑指offer》面试题16 反转链表 Java版
  • 原文地址:https://www.cnblogs.com/liguanzhen/p/8974505.html
Copyright © 2011-2022 走看看