python中pathlib模块的基本用法与总结


Posted in Python onAugust 17, 2020

前言

相比常用的 os.path而言,pathlib 对于目录路径的操作更简介也更贴近 Pythonic。但是它不单纯是为了简化操作,还有更大的用途。

pathlib 是Python内置库,Python 文档给它的定义是:The pathlib module ? object-oriented filesystem paths(面向对象的文件系统路径)。pathlib 提供表示文件系统路径的类,其语义适用于不同的操作系统。

python中pathlib模块的基本用法与总结

更多详细的内容可以参考官方文档:https://docs.python.org/3/library/pathlib.html#methods

1. pathlib模块下Path类的基本使用

from pathlib import Path

path = r'D:\python\pycharm2020\program\pathlib模块的基本使用.py'
p = Path(path)
print(p.name)  # 获取文件名
print(p.stem)  # 获取文件名除后缀的部分
print(p.suffix)  # 获取文件后缀
print(p.parent)  # 相当于dirname
print(p.parent.parent.parent)
print(p.parents) # 返回一个iterable 包含所有父目录
for i in p.parents:
 print(i)
print(p.parts)  # 将路径通过分隔符分割成一个元组

运行结果如下:

pathlib模块的基本使用.py
pathlib模块的基本使用
.py
D:\python\pycharm2020\program
D:\python
<WindowsPath.parents>
D:\python\pycharm2020\program
D:\python\pycharm2020
D:\python
D:\
('D:\\', 'python', 'pycharm2020', 'program', 'pathlib模块的基本使用.py')

  • Path.cwd():Return a new path object representing the current directory
  • Path.home():Return a new path object representing the user's home directory
  • Path.expanduser():Return a new path with expanded ~ and ~user constructs
from pathlib import Path

path_1 = Path.cwd()  # 获取当前文件路径
path_2 = Path.home()
p1 = Path('~/pathlib模块的基本使用.py')
print(path_1)
print(path_2)
print(p1.expanduser())

运行结果如下:

D:\python\pycharm2020\program
C:\Users\Administrator
C:\Users\Administrator\pathlib模块的基本使用.py

Path.stat():Return a os.stat_result object containing information about this path

from pathlib import Path
import datetime

p = Path('pathlib模块的基本使用.py')
print(p.stat())   # 获取文件详细信息
print(p.stat().st_size) # 文件的字节大小
print(p.stat().st_ctime) # 文件创建时间
print(p.stat().st_mtime) # 上次修改文件的时间
creat_time = datetime.datetime.fromtimestamp(p.stat().st_ctime)
st_mtime = datetime.datetime.fromtimestamp(p.stat().st_mtime)
print(f'该文件创建时间:{creat_time}')
print(f'上次修改该文件的时间:{st_mtime}')

运行结果如下:

os.stat_result(st_mode=33206, st_ino=3659174698076635, st_dev=3730828260, st_nlink=1, st_uid=0, st_gid=0, st_size=543, st_atime=1597366826, st_mtime=1597366826, st_ctime=1597320585)
543
1597320585.7657475
1597366826.9711637
该文件创建时间:2020-08-13 20:09:45.765748
上次修改该文件的时间:2020-08-14 09:00:26.971164

从不同.stat().st_属性 返回的时间戳表示自1970年1月1日以来的秒数,可以用datetime.fromtimestamp将时间戳转换为有用的时间格式。

Path.exists():Whether the path points to an existing file or directory
Path.resolve(strict=False):Make the path absolute,resolving any symlinks. A new path object is returned

from pathlib import Path

p1 = Path('pathlib模块的基本使用.py')   # 文件
p2 = Path(r'D:\python\pycharm2020\program') # 文件夹 
absolute_path = p1.resolve()
print(absolute_path)
print(Path('.').exists())
print(p1.exists(), p2.exists())
print(p1.is_file(), p2.is_file())
print(p1.is_dir(), p2.is_dir())
print(Path('/python').exists())
print(Path('non_existent_file').exists())

运行结果如下:

D:\python\pycharm2020\program\pathlib模块的基本使用.py
True
True True
True False
False True
True
False

Path.iterdir():When the path points to a directory,yield path objects of the directory contents

from pathlib import Path

p = Path('/python')
for child in p.iterdir():
  print(child)

运行结果如下:

\python\Anaconda
\python\EVCapture
\python\Evernote_6.21.3.2048.exe
\python\Notepad++
\python\pycharm-community-2020.1.3.exe
\python\pycharm2020
\python\pyecharts-assets-master
\python\pyecharts-gallery-master
\python\Sublime text 3

Path.glob(pattern):Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind),The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing.

Note:Using the “**” pattern in large directory trees may consume an inordinate amount of time

递归遍历该目录下所有文件,获取所有符合pattern的文件,返回一个generator。

获取该文件目录下所有.py文件

from pathlib import Path

path = r'D:\python\pycharm2020\program'
p = Path(path)
file_name = p.glob('**/*.py')
print(type(file_name))  # <class 'generator'>
for i in file_name:
  print(i)

获取该文件目录下所有.jpg图片

from pathlib import Path

path = r'D:\python\pycharm2020\program'
p = Path(path)
file_name = p.glob('**/*.jpg')
print(type(file_name))  # <class 'generator'>
for i in file_name:
  print(i)

获取给定目录下所有.txt文件、.jpg图片和.py文件

from pathlib import Path

def get_files(patterns, path):
  all_files = []
  p = Path(path)
  for item in patterns:
    file_name = p.rglob(f'**/*{item}')
    all_files.extend(file_name)
  return all_files

path = input('>>>请输入文件路径:')
results = get_files(['.txt', '.jpg', '.py'], path)
print(results)
for file in results:
  print(file)

Path.mkdir(mode=0o777, parents=False, exist_ok=False)

  • Create a new directory at this given path. If mode is given, it is combined with the process' umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.
  • If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
  • If parents is false (the default), a missing parent raises FileNotFoundError.
  • If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.
  • If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.

Changed in version 3.5: The exist_ok parameter was added.

Path.rmdir():Remove this directory. The directory must be empty.

from pathlib import Path

p = Path(r'D:\python\pycharm2020\program\test')
p.mkdir()
p.rmdir()
from pathlib import Path

p = Path(r'D:\python\test1\test2\test3')
p.mkdir(parents=True) # If parents is true, any missing parents of this path are created as needed
p.rmdir()  # 删除的是test3文件夹
from pathlib import Path

p = Path(r'D:\python\test1\test2\test3')
p.mkdir(exist_ok=True)
  • Path.unlink(missing_ok=False):Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead. If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist. If missing_ok is true, FileNotFoundError exceptions will be ignored. Changed in version 3.8:The missing_ok parameter was added.
  • Path.rename(target):Rename this file or directory to the given target, and return a new Path instance pointing to target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.
  • Path.open(mode=‘r', buffering=-1, encoding=None, errors=None, newline=None):Open the file pointed to by the path, like the built-in open() function does.
from pathlib import Path

p = Path('foo.txt')
p.open(mode='w').write('some text')
target = Path('new_foo.txt')
p.rename(target)
content = target.open(mode='r').read()
print(content)
target.unlink()

2. 与os模块用法的对比

python中pathlib模块的基本用法与总结

总结

到此这篇关于python中pathlib模块的基本用法与总结的文章就介绍到这了,更多相关python pathlib模块用法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python 读取excel文件生成sql文件实例详解
May 12 Python
python3.6+opencv3.4实现鼠标交互查看图片像素
Feb 26 Python
Python3.x爬虫下载网页图片的实例讲解
May 22 Python
浅析Python pandas模块输出每行中间省略号问题
Jul 03 Python
Python实现查找最小的k个数示例【两种解法】
Jan 08 Python
对python中Librosa的mfcc步骤详解
Jan 09 Python
Python可视化mhd格式和raw格式的医学图像并保存的方法
Jan 24 Python
python数据预处理之数据标准化的几种处理方式
Jul 17 Python
python 爬虫百度地图的信息界面的实现方法
Oct 27 Python
python本地文件服务器实例教程
May 02 Python
Python基于Tkinter开发一个爬取B站直播弹幕的工具
May 06 Python
Python  lambda匿名函数和三元运算符
Apr 19 Python
Pycharm无法打开双击没反应的问题及解决方案
Aug 17 #Python
详解python datetime模块
Aug 17 #Python
python实现梯度下降算法的实例详解
Aug 17 #Python
python3.5的包存放的具体路径
Aug 16 #Python
python根据字典的键来删除元素的方法
Aug 16 #Python
python实现取余操作的简单实例
Aug 16 #Python
python属于哪种语言
Aug 16 #Python
You might like
最简单的PHP程序--记数器
2006/10/09 PHP
mayfish 数据入库验证代码
2010/04/30 PHP
php file_put_contents()功能函数(集成了fopen、fwrite、fclose)
2011/05/24 PHP
php 生成自动创建文件夹并上传文件的示例代码
2014/03/07 PHP
ThinkPHP令牌验证实例
2014/06/18 PHP
php使用curl实现简单模拟提交表单功能
2017/05/15 PHP
php+croppic.js实现剪切上传图片功能
2018/08/14 PHP
跟着Jquery API学Jquery之一 选择器
2010/04/07 Javascript
仅IE9/10同时支持script元素的onload和onreadystatechange事件分析
2011/04/27 Javascript
浏览器解析js生成的html出现样式问题的解决方法
2012/04/16 Javascript
jQuery:delegate中select()不起作用的解决方法(实例讲解)
2014/01/26 Javascript
js调用iframe实现打印页面内容的方法
2014/03/04 Javascript
JavaScript中property和attribute的区别详细介绍
2015/03/03 Javascript
javascript解决IE6下hover问题的方法
2015/07/28 Javascript
HTML页面,测试JS对C函数的调用简单实例
2016/08/09 Javascript
利用JS屏蔽页面中的Enter按键提交表单的方法
2016/11/25 Javascript
jquery判断页面网址是否有效的两种方法
2016/12/11 Javascript
vue.js指令v-model使用方法
2017/03/20 Javascript
canvas轨迹回放功能实现
2017/12/20 Javascript
解决vue build打包之后首页白屏的问题
2018/03/06 Javascript
常用的 JS 排序算法 整理版
2018/04/05 Javascript
vue.js实现会动的简历(包含底部导航功能,编辑功能)
2019/04/08 Javascript
js判断在哪个浏览器打开项目的方法
2020/01/21 Javascript
[02:56]DOTA2矮人直升机 英雄基础教程
2013/11/26 DOTA
关于Python如何避免循环导入问题详解
2017/09/14 Python
通过Turtle库在Python中绘制一个鼠年福鼠
2020/02/03 Python
Python实现动态给类和对象添加属性和方法操作示例
2020/02/29 Python
Django User 模块之 AbstractUser 扩展详解
2020/03/11 Python
导致python中import错误的原因是什么
2020/07/01 Python
利用Python实现自动扫雷小脚本
2020/12/17 Python
Python第三方库安装缓慢的解决方法
2021/02/06 Python
大学生个人简历中的自我评价
2013/12/27 职场文书
六一儿童节主持词
2014/03/21 职场文书
2015年度校学生会工作总结报告
2015/05/23 职场文书
2015年小学远程教育工作总结
2015/07/28 职场文书
sql server 累计求和实现代码
2022/02/28 SQL Server