python中pathlib模块的基本用法与总结
作者:叶庭云 发布时间:2023-12-11 15:54:17
前言
相比常用的 os.path而言,pathlib 对于目录路径的操作更简介也更贴近 Pythonic。但是它不单纯是为了简化操作,还有更大的用途。
pathlib 是Python内置库,Python 文档给它的定义是:The pathlib module – object-oriented filesystem paths(面向对象的文件系统路径)。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模块用法的对比
来源:https://blog.csdn.net/fyfugoyfa/article/details/107991203


猜你喜欢
- Tensorflow数据读取有三种方式:Preloaded data: 预加载数据Feeding: Python产生数据,再把数据喂给后端。
- getAttribute该方法用来获取元素的属性,调用方式如下所示:object.getAttribute(attribute)以此前介绍的
- 最近在玩一个叫Baba is you的游戏,很羡慕里面的一个转场特效,所以试着做了一下。主要使用了JS和CSS,特效主要是用CSS实现的。H
- 一、任务概述26个英文字母识别是一个基于计算机视觉的图像分类任务,旨在从包含26个不同字母图像的数据集中训练一个深度学习模型,以对输入的字母
- 求最大连续子序列的和是一个很经典很古老的面试题了,记得在刚毕业找工作面试那会也遇到过同款问题。今儿突然想起来,正好快到毕业季,又该是苦逼的应
- 数据透视表(Pivot Table)是 Excel 中一个非常实用的分析功能,可以用于实现复杂的数据分类汇总和对比分析,是数据分析师和运营人
- 目录Java实现上传Excel文件并导出到数据库1、导入依赖2、domain3、utils4、Controller5、xmlJava实现上传
- Vue-router是伴随着Vue框架出现的路由系统,它也是公认的一种优秀的路由解决方案。在使用Vue-router时候,我们常常会使用其自
- 开发环境:python版本2.X#!/usr/bin/env python# -*- coding:utf-8 -*-# 适合python版
- 前言最近经历了一次服务器SQL SERVER 数据库服务器端事务日志爆满,导致服务器数据库写入不进数据的宕机事件,经过此次事件的发生,奉劝各
- 如何用JAVASCRIPT格式化数字成货币那种表示法?,比如说 34585962.00显示 为 34,585,962.00<scrip
- 最近面试,被问到一个题目,vue做一个按钮组件;当时只是说了一下思路,回来就附上代码。解决思路:通过父子组件通讯($refs 和 props
- MySQL的自增id都定义了初始值,然后不断加步长。虽然自然数没有上限,但定义了表示这个数的字节长度,计算机存储就有上限。比如,无符号整型(
- 在项目开发的过程中可能需要开放自己的数据库给别人,但是为了安全不能自己服务器里其他数据库同时开放。那么可以新建一个用户,给该用户开放特定数据
- 本文记录了mysql 5.7.16安装配置方法,具体内容如下第一步:下载下载地址滚动到下方就能看到了,根据自己的需求下载;我的电脑为64为的
- 今天设计models时,用到了choice这个属性,用来限制用户做出选择的范围。比如说性别的选择(男或女)。class User(Abstr
- 前言elasticsearch-dsl是基于elasticsearch-py封装实现的,提供了更简便的操作elasticsearch的方法。
- 摘要:本篇博客将详细介绍如何使用YOLOv5进行车牌识别模型的训练与评估。我们将搭建训练环境、准备数据、配置模型参数、启动训练过程,以及使用
- 好久没有更新博客了,今天看到论坛上有位朋友问起全屏布局,有点像vc的界面。来了兴趣,就写了一个。运用IE6的怪异模式,通过绝对定位来实现的。
- 关于电子邮件 大学之前,基本不用邮箱,所以基本感觉不到它的存在,也不知道有什么用;然而大学之后,随着认识的人越来越多,知识越来越广