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常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1