python内置库_pathlib学习笔记
2024-04-13 21:14:03
开发
78
介绍
官网资料
常见读操作
获取家目录
代码from pathlib import Path
print ( '获取家目录:' , Path. home( ) )
输出获取家目录: C:\Users\LiuJinBao
显示当前目录
代码from pathlib import Path
print ( '显示当前目录:' , Path. cwd( ) )
输出显示当前目录: D:\tools\NextCloud\Notes\jupyter\内置库\011pathlib
返回绝对路径
代码from pathlib import Path
file1 = Path( 'C:/windows/explorer.exe' )
print ( '返回绝对路径:' , file1. resolve( ) )
输出返回绝对路径: C:\Windows\explorer.exe
返回父目录
可叠加使用
代码from pathlib import Path
file1 = Path( 'C:/windows/explorer.exe' )
print ( '当前文件:' , file1, '父目录:' , file1. parent, '父目录的父目录:' , file1. parent. parent)
输出当前文件: C:\windows\explorer.exe 父目录: C:\windows 父目录的父目录: C:\
路径格式转换
代码from pathlib import PureWindowsPath
file1 = Path( 'C:/windows/explorer.exe' )
print ( "file1原来路径:" , str ( file1) , "转换后路径1:" , file1. as_uri( ) , "转换后路径2:" , file1. as_posix( ) )
输出file1原来路径: C:\windows\explorer.exe 转换后路径1: file:///C:/windows/explorer.exe 转换后路径2: C:/windows/explorer.exe
返回路径对象的相对路径
代码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) )
输出dir1: D:\jupyter\内置库 dir2: D:\jupyter dir1相对于dir2的相对路径 内置库
返回根目录(或盘符)
代码from pathlib import PureWindowsPath
file1 = Path( 'C:/windows/explorer.exe' )
print ( 'file1:' , file1, 'file1的根目录(或盘符):' , file1. anchor)
输出file1: C:\windows\explorer.exe file1的根目录(或盘符): C:\
返回文件信息
代码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) )
输出返回文件信息: 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
返回路径某个部分
代码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 ] )
输出返回整个路径: 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:\
返回展开了家目录的路径
代码from pathlib import PureWindowsPath
file1 = Path( '~/films/Monty' )
print ( file1. expanduser( ) )
输出C:\Users\LiuJinBao\films\Monty
根据旧路径返回新路径
代码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' ) )
输出返回整个路径: 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
判断是不是绝对路径
代码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( ) } " )
输出文件名称:/etc/passwd,是否为绝对路径:True
文件名称:passwd,是否为绝对路径:False
文件名称:c:\a\b,是否为绝对路径:True
文件名称:a\b,是否为绝对路径:False
判断一个路径是否是另一个路径的相对路径
如果不可计算,则抛出 ValueError
代码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) } " )
输出/etc/passwd是否为/etc的相对路径:True
/usr是否为/etc/passwd的相对路径:False
判断是不是目录或文件
代码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( ) )
输出判断是不是目录: c:\windows ______ True
判断是不是目录: C:\windows\system32\drivers\etc\hosts ______ False
判断是不是文件: c:\windows ______ False
判断是不是文件: C:\windows\system32\drivers\etc\hosts ______ True
判断目录或文件是否存在
代码from pathlib import Path
file1 = Path( 'C:/windows/system32/drivers/etc/hosts' )
print ( '判断目录或文件是否存在:' , file1, '______' , file1. exists( ) )
输出判断目录或文件是否存在: C:\windows\system32\drivers\etc\hosts ______ True
判断是否是符号连接文件
windows下的快捷方式不是符号连接文件
代码from pathlib import Path
file1 = Path( "E:/temp/temp2.lnk" )
file1. is_symlink( )
输出False
使用通配符返回目录下的文件
代码from pathlib import Path
homedir = Path. home( )
sorted ( homedir. glob( '*.dat.*' ) )
输出[WindowsPath('C:/Users/LiuJinBao/ntuser.dat.LOG1'),
WindowsPath('C:/Users/LiuJinBao/ntuser.dat.LOG2')]
路径连接
代码from pathlib import Path
dir1 = Path( "E:/temp/temp2" )
dir1. joinpath( 'test' , 'test2' )
输出WindowsPath('E:/temp/temp2/test/test2')
目录操作
创建目录
语法Path. mkdir( mode= 0o777 , parents= False , exist_ok= False )
选项
选项
说明
mode
它将与当前进程的 umask 值合并来决定文件模式和访问标志。如果路径已经存在,则抛出 FileExistsError。
parents
true:如果你目录存在则创建;false(默认):无你目录会导致 FileNotFoundError异常。
exist_ok
false(默认):目标已存在的情况下抛出 FileExistsError异常;true:忽略
代码dir1 = Path( 'E:/temp/temp123/test' )
dir1. mkdir( parents= True , exist_ok= True )
删除空目录
目录必须为空
代码from pathlib import Path
dir1 = Path( "E:/temp/temp123" )
dir1. rmdir( )
遍历目录
返回的是对象
代码from pathlib import Path
dir1 = Path( "E:/temp/" )
for i in dir1. iterdir( ) :
print ( i)
输出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
移动文件或目录
目标不能存在
如果目标文件存在,会抛出FileExistsError异常
代码from pathlib import Path
file1 = Path( 'E:/temp.txt' )
file1. rename( 'E:/temp2/temp.txt' )
输出将文件'E:/temp.txt' 移动到 'E:/temp2/temp.txt'
替换路径
重命名当前文件或文件夹
如果target所指示的文件或文件夹已存在,则覆盖原文件
效果是移动文件,不是复制文件
代码from pathlib import Path
file1 = Path( "E:/temp.txt" )
file2 = 'E:/temp2/temp.txt'
file1. replace( file2)
输出将文件'E:/temp.txt' 移动到 'E:/temp2/temp.txt'
文件操作
创建空文件
代码from pathlib import Path
file1 = Path( 'E:/temp.txt' )
file1. touch( mode= 0o666 , exist_ok= True )
写入文本文件
代码from pathlib import Path
file1 = Path( 'E:/temp.txt' )
file1. write_text( 'new words' )
复制文件
代码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)
代码from pathlib import Path
file1 = Path( 'E:/temp/test.txt' )
file1. chmod( 0o444 )
删除文件
使用前最好加上判断文件存在
代码from pathlib import Path
file1 = Path( 'test.txt' )
if file1. exists( ) :
file1. unlink( )
else :
print ( f' { file1} 文件不存在' )
读取文件
打开路径指向的文件,就像内置的 open() 函数所做的一样
读取结果类型为str
代码from pathlib import Path
file1 = Path( 'C:/windows/system32/drivers/etc/hosts' )
with file1. open ( ) as f:
f_all = f. read( )
print ( f_all)
输出# 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
读取结果类型为str
代码from pathlib import Path
file1 = Path( 'C:/windows/system32/drivers/etc/hosts' )
print ( file1. read_text( ) )
输出# 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
(略)
以字符串形式返回文本内容
打开路径指向的文件,就像内置的 open() 函数所做的一样
代码from pathlib import Path
file1 = Path( 'C:/windows/system32/drivers/etc/hosts' )
print ( file1. read_text( ) )
输出# 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
(略)
以字节对象的形式返回文件的内容
代码from pathlib import Path
file1 = Path( 'C:/windows/system32/drivers/etc/hosts' )
print ( file1. read_bytes( ) )
输出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"
自定义函数
如果文件达到指定大小,则移动文件
代码from pathlib import Path
def move_file ( file1, size, 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)
根据指定文件获取用户名和密码
代码from pathlib import Path
def GetPasswd ( 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)
删除过期文件(不含目录)
代码
from pathlib import Path
from datetime import datetime
def delFiles ( 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)
原文地址:https://blog.csdn.net/liujinbao8000/article/details/137595153
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:https://www.suanlizi.com/kf/1779135962161483776.html
如若内容造成侵权/违法违规/事实不符,请联系《酸梨子》网邮箱:1419361763@qq.com进行投诉反馈,一经查实,立即删除!