python内置库_pathlib学习笔记

2024-04-10 16:28

本文主要是介绍python内置库_pathlib学习笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 介绍
    • 常见读操作
      • 获取家目录
      • 显示当前目录
      • 返回绝对路径
      • 返回父目录
      • 路径格式转换
      • 返回路径对象的相对路径
      • 返回根目录(或盘符)
      • 返回文件信息
      • 返回路径某个部分
      • 返回展开了家目录的路径
      • 根据旧路径返回新路径
      • 判断是不是绝对路径
      • 判断一个路径是否是另一个路径的相对路径
      • 判断是不是目录或文件
      • 判断目录或文件是否存在
      • 判断是否是符号连接文件
      • 使用通配符返回目录下的文件
      • 路径连接
    • 目录操作
      • 创建目录
      • 删除空目录
      • 遍历目录
      • 移动文件或目录
      • 替换路径
    • 文件操作
      • 创建空文件
      • 写入文本文件
      • 复制文件
      • 改变文件的模式和权限(多用于Linux)
      • 删除文件
      • 读取文件
      • 读取文件2
      • 以字符串形式返回文本内容
      • 以字节对象的形式返回文件的内容
    • 自定义函数
      • 如果文件达到指定大小,则移动文件
      • 根据指定文件获取用户名和密码
      • 删除过期文件(不含目录)

介绍

  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移动到file2file_byte = size * 1024 *1024if 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,passwordusername,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}')continuedelFiles(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)
    

这篇关于python内置库_pathlib学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/891567

相关文章

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息