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

前言

相比常用的 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模块用法的对比

总结

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

(0)

相关推荐

  • Python中的pathlib.Path为什么不继承str详解

    起步 既然所有路径都可以表示为字符串,为什么 pathlib.Path 不继承 str ? 这个想法的提出在 https://mail.python.org/pipermail//python-ideas/2016-April/039475.html 可以看到,其中,还提出了将 p'/some/path/to/a/file' 返回 path.Path 实例的想法. 路径都是字符串吗? 从面向对象的继承的思想来看,如果 Path 继承自 str ,那么所有的路径都应该是字符串.但所有的路径都是字符

  • 对python3中pathlib库的Path类的使用详解

    用了很久的os.path,今天发现竟然还有这么好用的库,记录下来以便使用. 1.调用库 from pathlib import 2.创建Path对象 p = Path('D:/python/1.py') print(p) #可以这么使用,相当于os.path.join() p1 = Path('D:/python') p2 = p1/'123' print(p2) 结果 D:\python\1.py D:\python\123 3.Path.cwd() 获取当前路径 path = Path.cw

  • python3 pathlib库Path类方法总结

    这篇文章主要介绍了python3 pathlib库Path类方法总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.调用库 from pathlib import Path 2.创建path对象 p = Path(file) 3.方法总结 p.cwd() # 获取当前路径 p.stat() # 获取当前文件的信息 p.exists() # 判断当前路径是否是文件或者文件夹 p.glob(filename) # 获取路径下的所有符合filen

  • 详谈Python3 操作系统与路径 模块(os / os.path / pathlib)

    以下代码以Python3.6.1 / windows10为例 Less is more! #!/usr/bin/env python # coding=utf-8 __author__ = 'Luzhuo' __date__ = '2017/5/7' import os def os_demo(): # 执行命令 dirs = os.popen("dir").read() print(dirs) # 打印目录树 dirs_info = os.scandir() for info in

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

    前言 相比常用的 os.path而言,pathlib 对于目录路径的操作更简介也更贴近 Pythonic.但是它不单纯是为了简化操作,还有更大的用途. pathlib 是Python内置库,Python 文档给它的定义是:The pathlib module – object-oriented filesystem paths(面向对象的文件系统路径).pathlib 提供表示文件系统路径的类,其语义适用于不同的操作系统. 更多详细的内容可以参考官方文档:https://docs.python.

  • Python中threading模块join函数用法实例分析

    本文实例讲述了Python中threading模块join函数用法.分享给大家供大家参考.具体分析如下: join的作用是众所周知的,阻塞进程直到线程执行完毕.通用的做法是我们启动一批线程,最后join这些线程结束,例如: for i in range(10): t = ThreadTest(i) thread_arr.append(t) for i in range(10): thread_arr[i].start() for i in range(10): thread_arr[i].joi

  • Python中os模块功能与用法详解

    本文实例讲述了Python中os模块功能与用法.分享给大家供大家参考,具体如下: OS模块 Python的os模块封装了常见的文件和目录操作,本文只是列出部分常用的方法,更多的方法可以查看官方文档. 下面是部分常见的用法: 方法 说明 os.mkdir 创建目录 os.rmdir 删除目录 os.rename 重命名 os.remove 删除文件 os.getcwd 获取当前工作路径 os.walk 遍历目录 os.path.join 连接目录与文件名 os.path.split 分割文件名与目

  • Python中sys模块功能与用法实例详解

    本文实例讲述了Python中sys模块功能与用法.分享给大家供大家参考,具体如下: sys-系统特定的参数和功能 该模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数.它始终可用. sys.argv 传递给Python脚本的命令行参数列表.argv[0]是脚本名称(依赖于操作系统,无论这是否是完整路径名).如果使用-c解释器的命令行选项执行命令,argv[0]则将其设置为字符串'-c'.如果没有脚本名称传递给Python解释器,argv[0]则为空字符串. 要循环标准输入或命

  • Python中os模块的实例用法

    1.说明 os.path.exists():用于判断某个路径(文件或文件夹)是否存在,若存在则返回True,若不存在则返回False. os.makedirs():用于创建文件夹.传入所欲创建的文件夹的路径即可,没有返回值.值得一提的是,这个函数可以实现目录的递归创建,也就是说如果所传入的路径中,倒数第二级的目录也不存在,那么就会先创建该级目录,然后在在目录下创建所欲创建的目录,依此类推. os.path.basename():传入一个文件的路径,返回该文件的文件名. os.path.dirna

  • Python中pywifi模块的基本用法讲解

      跨平台的pywifi模块支持操作无线网卡,该模块易于使用,同时支持Windows.Linux等多个系统.pywifi模块不是Python的标准模块,需单独安装,同时该模块依赖comtypes模块,最好同时安装comtypes模块,否则调用pywifi的函数时可能会报错. pip install comtypes pip install pywifi   pywifi模块中的类不算太多,其中主要用到的类包括PyWiFi.Profile.Interface等,详述如下:  PyWiFi类用于操作

  • python中xlwt模块的具体用法

    目录 一.前言 二.基础操作 三.样式优化 1.设置行列宽度 2.设置文本居中 3.设置边框 4.设置字体样式 5.综合代码 一.前言 xlwt模块是python中专门用于写入Excel的拓展模块,可以实现创建表单.写入指定单元格.指定单元格样式等人工实现的功能,一句话就是人使用excel实现的功能,这个扩展包都可以实现. 二.基础操作 1.创建workbook(创建excel) #创建一个工作簿对象,设置编码格式为"utf-8",默认格式是ASCII,为了方便写入中文,一般都要设置成

  • Python中XlsxWriter模块简介与用法分析

    本文实例讲述了Python中XlsxWriter模块用法.分享给大家供大家参考,具体如下: XlsxWriter,可以生成excel文件(xlsx的哦),然后很重要的一点就是,它不仅仅只是生成数据,还能插入直方图,饼图-.,使用条件格式,合并单元格等等这些操作.话不多说,先上图,在上例子哈! 以直方图为例子哈 生成文体效果如下 代码解析 # -*- coding: cp936 -*- import xlsxwriter workbook = xlsxwriter.Workbook('chart_

  • python中pygame模块用法实例

    本文实例讲述了python中pygame模块用法,分享给大家供大家参考.具体方法如下: import pygame, sys from pygame.locals import * #set up pygame pygame.init() windowSurface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("hello, world") BLACK = (0, 0, 0) WHITE

  • python中string模块各属性以及函数的用法介绍

    任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作. python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求: • python的字符串属性函数 • python的string模块 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1.字符串属性函数  系统版本:CentOS release 6.2 (Final)2.6.32-220.

随机推荐