前言

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

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

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

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)) #

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)) #

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博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

python中path的用法_python中pathlib模块的基本用法与总结相关推荐

  1. python中os.path.join()的循环用法_python中使用os.path.join()

    os.path.join的详细解释请移步os.path模块 在使用的过程中,我使用如下代码: import os path = "F:/gts/gtsdate/" b = os.p ...

  2. python or的用法_python中and和or的用法

    原博文 2013-01-19 13:40 − From <dive into python> python 中的and从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第 ...

  3. python常用函数的用法_python中常用函数整理

    1.map map是python内置的高阶函数,它接收一个函数和一个列表,函数依次作用在列表的每个元素上,返回一个可迭代map对象. class map(object):""&qu ...

  4. python中sys用法_Python中sys模块功能与用法实例详解

    Python中sys模块功能与用法.,具体如下: sys-系统特定的参数和功能 该模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数.它始终可用. sys.argv 传递给Pyth ...

  5. python中byte2array报错_python基础-bytes和bytearray的用法

    Python中的序列类型有bytes和bytearray. 二进制序列类型的用法比较少见,是python中少用的一种序列类型,对于二进制序列类型,大家基本了解即可. bytes二进制序列类型 指定长度 ...

  6. python里try和except用法_Python中的错误和异常处理简单操作示例【try-except用法】...

    本文实例讲述了Python中的错误和异常处理操作.分享给大家供大家参考,具体如下: #coding=utf8 print ''''' 程序编译时会检测语法错误. 当检测到一个错误,解释器会引发一个异常 ...

  7. python中zeros用法_python中numpy.zeros(np.zeros)的使用方法

    python 的 python中numpy.zeros(np.zeros)的使用方法 翻译: 用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和 ...

  8. python正则findall函数的用法_python中正则表达式 re.findall 用法

    python中正则表达式 re.findall 用法 Python 正则表达式 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配. Python 自1.5版本起增加了r ...

  9. python中all的用法_python中all用法

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 开发准备cas 的 python sdk 包含了用于访问和操作 cas 的所有 ...

  10. python not用法_python中not、and和or的优先级与详细用法介绍

    前言 (小白专用)本次所分享的是python中的not.and.or的执行时的优先级,以及他们的具体用法.本文比较详细,不喜勿喷. 一.not.and.or的含义以及优先级 对象 返回结果 优先顺序 ...

最新文章

  1. Bootstrap4 更新笔记
  2. sublime如何实现函数折叠
  3. DFTug Test_point
  4. 2017年11月04日普及组 Biotech
  5. java 队列的数组_JAVA-循环数组实现简单的队列
  6. 一个平庸程序员的自白
  7. python有趣的简单代码_简单几步,100行代码用Python画一个蝙蝠侠的logo
  8. java国际规范标准,国际化 - Java Servlet 3.1 规范
  9. CSS3新单位vw,vh,vmin,vmax详解
  10. URAL 1004 Sightseeing trip
  11. C语言编程规范(排版)
  12. apache worker性能调优
  13. java 内部邮件_java – 来自内部存储的电子邮件
  14. 一个医院内的计算机网络系统属于,医院信息管理系统
  15. 使用Unity创建一个游戏场景
  16. 终面(HR面)_职业竞争力和职业规划
  17. python如何编写温度转换_Python温度转换实例分析
  18. 2020用户行为分析领域最具商业合作价值企业盘点
  19. 停用计算机网络,如何禁用电脑上网功能
  20. iphone计算机要电话,有了这个神器,在PC上也能接听iPhone电话、收发短息啦(安卓也可以哦~)...

热门文章

  1. JAVA教程下载-JAVA学习视频教程网盘分享
  2. Winform使用FTP实现自动更新
  3. 高等数学在计算机中的应用论文1500字,大学高等数学论文范文
  4. PHP编写学生信息表格
  5. garmin 945_点评:Garmin Nuvi 350 GPS
  6. 【实验报告】LFM信号产生与频谱分析(记录一次实验:《电类综合实验》)
  7. JavaScript全套视频教程
  8. html + css 实现淘宝首页(静态页面)
  9. DBC2000是什么?DBC2000数据库文件详解
  10. java下载文件excel格式错乱,excel表格数据错乱如何修复-excel表格里的文件突然格式全部乱了,怎么恢复?...