python内置库_pathlib学习笔记

介绍

  1. 官网资料

常见读操作

获取家目录

  1. 代码
    from pathlib import Path
    print('获取家目录:',Path.home())
    
  2. 输出
    获取家目录: C:\Users\LiuJinBao
    

显示当前目录

  1. 代码
    from pathlib import Path
    print('显示当前目录:',Path.cwd())
    
  2. 输出
    显示当前目录: D:\tools\NextCloud\Notes\jupyter\内置库\011pathlib
    

返回绝对路径

  1. 代码
    from pathlib import Path
    file1 = Path('C:/windows/explorer.exe')
    print('返回绝对路径:',file1.resolve())
    
  2. 输出
    返回绝对路径: C:\Windows\explorer.exe
    

返回父目录

  1. 可叠加使用
  2. 代码
    from pathlib import Path
    file1 = Path('C:/windows/explorer.exe')
    print('当前文件:',file1,'父目录:',file1.parent,'父目录的父目录:',file1.parent.parent)
    
  3. 输出
    当前文件: C:\windows\explorer.exe 父目录: C:\windows 父目录的父目录: C:\
    

路径格式转换

  1. 代码
    from pathlib import PureWindowsPath
    file1 = Path('C:/windows/explorer.exe')
    print("file1原来路径:",str(file1),"转换后路径1:",file1.as_uri(),"转换后路径2:",file1.as_posix())
    
  2. 输出
    file1原来路径: C:\windows\explorer.exe 转换后路径1: file:///C:/windows/explorer.exe 转换后路径2: C:/windows/explorer.exe
    

返回路径对象的相对路径

  1. 代码
    from pathlib import PureWindowsPath
    dir1 = Path(r'D:\jupyter\内置库')
    dir2 = Path(r'D:\jupyter')
    print ('dir1:',dir1,'dir2:',dir2,'  dir1相对于dir2的相对路径',dir1.relative_to(dir2))
    
  2. 输出
    dir1: D:\jupyter\内置库 dir2: D:\jupyter   dir1相对于dir2的相对路径 内置库
    

返回根目录(或盘符)

  1. 代码
    from pathlib import PureWindowsPath
    file1 = Path('C:/windows/explorer.exe')
    print('file1:',file1,'file1的根目录(或盘符):',file1.anchor)
    
  2. 输出
    file1: C:\windows\explorer.exe file1的根目录(或盘符): C:\
    

返回文件信息

  1. 代码
    from datetime import date
    from pathlib import PureWindowsPath
    file1 = Path('C:/windows/explorer.exe')
    print('返回文件信息:',file1.stat())
    #文件创建时间
    time2 = file1.stat().st_ctime
    # 時間戳转换为日期
    print('返回文件创建时间:',date.fromtimestamp(time2))
    
  2. 输出
    返回文件信息: os.stat_result(st_mode=33279, st_ino=562949953771609, st_dev=3148138506, st_nlink=2, st_uid=0, st_gid=0, st_size=4968224, st_atime=1646654758, st_mtime=1645926532, st_ctime=1645926532)
    返回文件创建时间: 2022-02-27
    

返回路径某个部分

  1. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/http.sys')
    print('返回整个路径:',str(file1))
    print('返回父目录,可叠加使用:',file1.parent)
    print('返回驱动器和根的联合:',file1.anchor)
    print('返回驱动器部分:',file1.drive)
    print('返回根部分:',file1.root)
    print('返回文件名部分:',file1.name)
    print('返回主文件名部分:',file1.stem)
    print('返回扩展名部分:',file1.suffix)
    print('返回扩展名列表:',file1.suffixes)
    print('返回第1个部分:',file1.parents[0])
    print('返回第2个部分:',file1.parents[1])
    print('返回第3个部分:',file1.parents[2])
    print('返回第4个部分:',file1.parents[3])
    
  2. 输出
    返回整个路径: C:\windows\system32\drivers\http.sys
    返回父目录,可叠加使用: C:\windows\system32\drivers
    返回驱动器和根的联合: C:\
    返回驱动器部分: C:
    返回根部分: \
    返回文件名部分: http.sys
    返回主文件名部分: http
    返回扩展名部分: .sys
    返回扩展名列表: ['.sys']
    返回第1个部分: C:\windows\system32\drivers
    返回第2个部分: C:\windows\system32
    返回第3个部分: C:\windows
    返回第4个部分: C:\
    

返回展开了家目录的路径

  1. 代码
    from pathlib import PureWindowsPath
    file1 = Path('~/films/Monty')
    print(file1.expanduser())
    
  2. 输出
    C:\Users\LiuJinBao\films\Monty
    

根据旧路径返回新路径

  1. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/http.sys')
    print('返回整个路径:',str(file1))
    print('返回路径修改name:',file1.with_name('setup.py'))
    print('返回路径修改主文件名:',file1.with_stem('final'))
    print('返回路径修改扩展名:',file1.with_suffix('.bz2'))
    
  2. 输出
    返回整个路径: C:\windows\system32\drivers\http.sys
    返回路径修改name: C:\windows\system32\drivers\setup.py
    返回路径修改主文件名: C:\windows\system32\drivers\final.sys
    返回路径修改扩展名: C:\windows\system32\drivers\http.bz2
    

判断是不是绝对路径

  1. 代码
    from pathlib import PurePosixPath
    from pathlib import PureWindowsPath
    file1 = PurePosixPath('/etc/passwd')
    file2 = PurePosixPath("passwd")
    file3 = PureWindowsPath('c:/a/b')
    file4 = PureWindowsPath('a/b')
    print(f"文件名称:{ file1 },是否为绝对路径:{ file1.is_absolute() }")
    print(f"文件名称:{ file2 },是否为绝对路径:{ file2.is_absolute() }")
    print(f"文件名称:{ file3 },是否为绝对路径:{ file3.is_absolute() }")
    print(f"文件名称:{ file4 },是否为绝对路径:{ file4.is_absolute() }")
    
  2. 输出
    文件名称:/etc/passwd,是否为绝对路径:True
    文件名称:passwd,是否为绝对路径:False
    文件名称:c:\a\b,是否为绝对路径:True
    文件名称:a\b,是否为绝对路径:False
    

判断一个路径是否是另一个路径的相对路径

  1. 如果不可计算,则抛出 ValueError
  2. 代码
    from pathlib import PurePosixPath
    file1 = PurePosixPath('/etc/passwd')
    file2 = PurePosixPath('/etc')
    file3 = PurePosixPath('/usr')
    print(f"{ file1 }是否为{ file2 }的相对路径:{ file1.is_relative_to(file2) }")
    print(f"{ file3 }是否为{ file1 }的相对路径:{ file1.is_relative_to(file3) }")
    
  3. 输出
    /etc/passwd是否为/etc的相对路径:True
    /usr是否为/etc/passwd的相对路径:False
    

判断是不是目录或文件

  1. 代码
    from pathlib import Path
    path1 = Path('c:\windows')
    file1 = Path('C:/windows/system32/drivers/etc/hosts')
    print('判断是不是目录:',path1,'______',path1.is_dir())
    print('判断是不是目录:',file1,'______',file1.is_dir())
    print('判断是不是文件:',path1,'______',path1.is_file())
    print('判断是不是文件:',file1,'______',file1.is_file())
    
  2. 输出
    判断是不是目录: c:\windows ______ True
    判断是不是目录: C:\windows\system32\drivers\etc\hosts ______ False
    判断是不是文件: c:\windows ______ False
    判断是不是文件: C:\windows\system32\drivers\etc\hosts ______ True
    

判断目录或文件是否存在

  1. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/etc/hosts')
    print('判断目录或文件是否存在:',file1,'______',file1.exists())
    
  2. 输出
    判断目录或文件是否存在: C:\windows\system32\drivers\etc\hosts ______ True
    

判断是否是符号连接文件

  1. windows下的快捷方式不是符号连接文件
  2. 代码
    from pathlib import Path
    file1 = Path("E:/temp/temp2.lnk")
    file1.is_symlink()
    
  3. 输出
    False
    

使用通配符返回目录下的文件

  1. 代码
    from pathlib import Path
    homedir = Path.home()
    sorted(homedir.glob('*.dat.*'))
    
  2. 输出
    [WindowsPath('C:/Users/LiuJinBao/ntuser.dat.LOG1'),
     WindowsPath('C:/Users/LiuJinBao/ntuser.dat.LOG2')]
    

路径连接

  1. 代码
    from pathlib import Path
    dir1 = Path("E:/temp/temp2")
    dir1.joinpath('test','test2')
    
  2. 输出
    WindowsPath('E:/temp/temp2/test/test2')
    

目录操作

创建目录

  1. 语法
    Path.mkdir(mode=0o777, parents=False, exist_ok=False)
    
  2. 选项
    选项说明
    mode它将与当前进程的 umask 值合并来决定文件模式和访问标志。如果路径已经存在,则抛出 FileExistsError。
    parentstrue:如果你目录存在则创建;false(默认):无你目录会导致 FileNotFoundError异常。
    exist_okfalse(默认):目标已存在的情况下抛出 FileExistsError异常;true:忽略
  3. 代码
    dir1 = Path('E:/temp/temp123/test')
    dir1.mkdir(parents=True,exist_ok=True)
    

删除空目录

  1. 目录必须为空
  2. 代码
    from pathlib import Path
    dir1 = Path("E:/temp/temp123")
    dir1.rmdir()
    

遍历目录

  1. 返回的是对象
  2. 代码
    from pathlib import Path
    dir1 = Path("E:/temp/")
    for i in dir1.iterdir():
        print(i)
    
  3. 输出
    E:\temp\EasyU_3.7.2022.0215_VIP
    E:\temp\EasyU_3.7.2022.0215_VIP.7z
    E:\temp\ventoy-1.0.70-windows
    E:\temp\ventoy-1.0.70-windows.zip
    

移动文件或目录

  1. 目标不能存在
  2. 如果目标文件存在,会抛出FileExistsError异常
  3. 代码
    from pathlib import Path
    file1 = Path('E:/temp.txt')
    file1.rename('E:/temp2/temp.txt')
    
  4. 输出
    将文件'E:/temp.txt'  移动到  'E:/temp2/temp.txt'
    

替换路径

  1. 重命名当前文件或文件夹
  2. 如果target所指示的文件或文件夹已存在,则覆盖原文件
  3. 效果是移动文件,不是复制文件
  4. 代码
    from pathlib import Path
    file1 = Path("E:/temp.txt")
    file2 = 'E:/temp2/temp.txt'
    file1.replace(file2)
    
  5. 输出
    将文件'E:/temp.txt'  移动到  'E:/temp2/temp.txt'
    

文件操作

创建空文件

  1. 代码
    from pathlib import Path
    file1 = Path('E:/temp.txt')
    file1.touch(mode=0o666, exist_ok=True)
    

写入文本文件

  1. 代码
    from pathlib import Path
    file1 = Path('E:/temp.txt')
    file1.write_text('new words')
    

复制文件

  1. 代码
    from pathlib import Path
    file_dest = Path('dest')
    file_src = Path('src')
    file_dest.write_bytes(file_src.read_bytes()) # 复制二进制文件
    file_dest.write_text(file_src.read_text()) # 复制文本文件
    

改变文件的模式和权限(多用于Linux)

  1. 代码
    from pathlib import Path
    file1 = Path('E:/temp/test.txt')
    file1.chmod(0o444)
    #print('改变文件的模式和权限(linux系统):',file1.chmod(0o444))
    

删除文件

  1. 使用前最好加上判断文件存在
  2. 代码
    from pathlib import Path
    file1 = Path('test.txt')
    if file1.exists():
        file1.unlink()
    else:
        print(f'{file1}文件不存在')
    

读取文件

  1. 打开路径指向的文件,就像内置的 open() 函数所做的一样
  2. 读取结果类型为str
  3. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/etc/hosts')
    with file1.open() as f:
        f_all = f.read()
    print(f_all)
    
  4. 输出
    # Copyright (c) 1993-2009 Microsoft Corp.
    #
    # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
    #
    # This file contains the mappings of IP addresses to host names. Each
    (略)
    

读取文件2

  1. 读取结果类型为str
  2. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/etc/hosts')
    print(file1.read_text())
    
  3. 输出
    # Copyright (c) 1993-2009 Microsoft Corp.
    #
    # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
    #
    # This file contains the mappings of IP addresses to host names. Each
    (略)
    

以字符串形式返回文本内容

  1. 打开路径指向的文件,就像内置的 open() 函数所做的一样
  2. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/etc/hosts')
    print(file1.read_text())
    
  3. 输出
    # Copyright (c) 1993-2009 Microsoft Corp.
    #
    # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
    #
    # This file contains the mappings of IP addresses to host names. Each
    (略)
    

以字节对象的形式返回文件的内容

  1. 代码
    from pathlib import Path
    file1 = Path('C:/windows/system32/drivers/etc/hosts')
    print(file1.read_bytes())
    
  2. 输出
    b"# Copyright (c) 1993-2009 Microsoft Corp.\r\n#\r\n# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.\r\n#\r\n# This file contains the mappings of IP addresses to host names. Each\r\n# entry should be kept on an individual line. The IP address should\r\n# be placed in the first column followed by the corresponding host name.\r\n# The IP address and the host name should be separated by at least one\r\n# space.\r\n#\r\n# Additionally, comments (such as these) may be inserted on individual\r\n# lines or following the machine name denoted by a '#' symbol.\r\n#\r\n# For example:\r\n#\r\n#      102.54.94.97     rhino.acme.com          # source server\r\n#       38.25.63.10     x.acme.com              # x client host\r\n\r\n# localhost name resolution is handled within DNS itself.\r\n#\t127.0.0.1       localhost\r\n#\t::1             localhost\r\n127.0.0.1       activate.navicat.com\r\n169.254.220.138 windows10.microdone.cn\r\n"
    

自定义函数

如果文件达到指定大小,则移动文件

  1. 代码
    from pathlib import Path
    
    ################################### 自定义函数_如果文件达到指定大小,则移动文件 ####################################
    def move_file(file1,size,file2):
        # 如果file1文件大小有size M则将file1移动到file2
        file_byte = size * 1024 *1024
        if file1.exists():
            if file_byte < file1.stat().st_size:
                if not file1.exists():
                    print("源文件不存在")
                elif file2.exists():
                    print("目标文件已存在,无法移动")
                else:
                    print("文件大小满足,正在移动文件...")
                    file1.rename(file2)
                    if file2.exists():
                        print("文件移动成功")
            else:
                print("文件太小,无需移动")
        else:
            print(f"文件{file1}不存在")
    
    if __name__ == '__main__':
    
        file1 = Path("d:\\Notes.7z")
        file2 = Path("d:\\tools\\Notes_bak.7z")
        move_file(file1,60,file2)
    

根据指定文件获取用户名和密码

  1. 代码
    from pathlib import Path
    
    ################################### 自定义函数_根据文件获取用户名和密码 ####################################
    def GetPasswd(filename):
        # filename文件格式为:用户名,密码
        # 用户名和密码的首位和末位不能是空字符
        filename = Path(filename)
        with filename.open() as f:
            con = f.read()
        username = con.split(",")[0].strip()
        password = con.split(",")[1].strip()
        return username,password
       
    username,password = GetPasswd('/mnt/share/bak/var_files/passwd_core.txt')
    print(username)
    print(password)
    

删除过期文件(不含目录)

  1. 代码
    #!/usr/bin/python3
    from pathlib import Path
    from datetime import datetime
    
    ######################################## 自定义函数_删除过期文件(不含目录) ########################################
    def delFiles(beforeSec, dirpath, dir_exclude):
        # beforeSec的单位为秒, dirpath为操作哪个目录, dir_exclude为排除目录, 是一个列表, 元素为子目录名称
        print("检查的目录为:",dirpath)
        for i in dirpath.iterdir():
            if i.is_file:
                if i.stat().st_ctime < beforeSec:
                    try:
                        i.unlink()
                        print(f'删除文件:{i}')
                    except Exception as e:
                        print(e)
            if i.is_dir():
                if i.name in dir_exclude:
                    print(f'跳过排除目录:{i}')
                    continue
                delFiles(beforeSec, i, dir_exclude)
    
    # 删除过期目录
    beforeDay = 3
    beforeSec = datetime.timestamp(datetime.now()) - 3600 * 24 * beforeDay
    dir_exclude = ['jpg_base']
    dir_main = Path('/mnt/sdb1/share/camera/')
    delFiles(beforeSec, dir_main, dir_exclude)
    
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liujinbao8000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值