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中操作mysql的pymysql模块详解
Sep 13 Python
python 性能优化方法小结
Mar 31 Python
python使用 HTMLTestRunner.py生成测试报告
Oct 20 Python
Python3爬虫学习之爬虫利器Beautiful Soup用法分析
Dec 12 Python
在Python中os.fork()产生子进程的例子
Aug 08 Python
简单介绍python封装的基本知识
Aug 10 Python
python基于FTP实现文件传输相关功能代码实例
Sep 28 Python
python numpy之np.random的随机数函数使用介绍
Oct 06 Python
Python实现AI自动抠图实例解析
Mar 05 Python
python能否java成为主流语言吗
Jun 22 Python
python实现三阶魔方还原的示例代码
Apr 28 Python
Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析
Oct 16 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
如何用phpmyadmin设置mysql数据库用户的权限
2012/01/09 PHP
PHP过滤★等特殊符号的正则
2014/01/27 PHP
PHPAnalysis中文分词类详解
2014/06/13 PHP
PHP实现HTTP断点续传的方法
2015/06/17 PHP
PHP简单实现欧拉函数Euler功能示例
2017/11/06 PHP
PHP一致性hash分布式算法封装类定义与用法示例
2018/08/04 PHP
js 获取和设置css3 属性值的实现方法
2013/05/06 Javascript
JS写的贪吃蛇游戏(个人练习)
2013/07/08 Javascript
js清空表单数据的两种方式(遍历+reset)
2014/07/18 Javascript
JavaScript中实现单体模式分享
2015/01/29 Javascript
jQuery实现的Div窗口震动效果实例
2015/08/07 Javascript
JavaScript对象数组的排序处理方法
2015/10/21 Javascript
使用JavaScript根据图片获取条形码的方法
2017/07/04 Javascript
node.js爬取中关村的在线电瓶车信息
2018/11/13 Javascript
layer 关闭指定弹出层的例子
2019/09/25 Javascript
jQuery实现开关灯效果
2020/08/02 jQuery
Vue使用Ref跨层级获取组件的步骤
2021/01/25 Vue.js
Python模块学习 re 正则表达式
2011/05/19 Python
Python 使用PIL中的resize进行缩放的实例讲解
2018/08/03 Python
对web.py设置favicon.ico的方法详解
2018/12/04 Python
在Python文件中指定Python解释器的方法
2019/02/18 Python
python3.6+django2.0+mysql搭建网站过程详解
2019/07/24 Python
python连接、操作mongodb数据库的方法实例详解
2019/09/11 Python
DJango的创建和使用详解(默认数据库sqlite3)
2019/11/18 Python
Python ORM框架Peewee用法详解
2020/04/29 Python
django数据模型中null和blank的区别说明
2020/09/02 Python
Crocs波兰官方商店:女鞋、男鞋、童鞋、洞洞鞋
2019/10/08 全球购物
什么是类的返射机制
2016/02/06 面试题
中间件的定义
2016/08/09 面试题
我的求职计划书
2014/01/10 职场文书
求职信模板标准格式范文
2014/02/23 职场文书
师范生求职信
2014/06/14 职场文书
刘公岛导游词
2015/02/05 职场文书
房地产工程部经理岗位职责
2015/04/09 职场文书
干货:如何写好观后感 !
2019/05/21 职场文书
Python制作动态字符画的源码
2021/08/04 Python