电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

python中pathlib模塊的基本用法與總結

瀏覽:5日期:2022-07-13 18:56:59

前言

相比常用的 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 Pathpath = r’D:pythonpycharm2020programpathlib模塊的基本使用.py’p = Path(path)print(p.name) # 獲取文件名print(p.stem) # 獲取文件名除后綴的部分print(p.suffix) # 獲取文件后綴print(p.parent) # 相當于dirnameprint(p.parent.parent.parent)print(p.parents) # 返回一個iterable 包含所有父目錄for i in p.parents: print(i)print(p.parts) # 將路徑通過分隔符分割成一個元組

運行結果如下:

pathlib模塊的基本使用.pypathlib模塊的基本使用.pyD:pythonpycharm2020programD:python<WindowsPath.parents>D:pythonpycharm2020programD:pythonpycharm2020D:pythonD:(’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 Pathpath_1 = Path.cwd() # 獲取當前文件路徑path_2 = Path.home()p1 = Path(’~/pathlib模塊的基本使用.py’)print(path_1)print(path_2)print(p1.expanduser())

運行結果如下:

D:pythonpycharm2020programC:UsersAdministratorC:UsersAdministratorpathlib模塊的基本使用.py

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

from pathlib import Pathimport datetimep = 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)5431597320585.76574751597366826.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 directoryPath.resolve(strict=False):Make the path absolute,resolving any symlinks. A new path object is returned

from pathlib import Pathp1 = Path(’pathlib模塊的基本使用.py’) # 文件p2 = Path(r’D:pythonpycharm2020program’) # 文件夾 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:pythonpycharm2020programpathlib模塊的基本使用.pyTrueTrue TrueTrue FalseFalse TrueTrueFalse

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

from pathlib import Pathp = Path(’/python’)for child in p.iterdir(): print(child)

運行結果如下:

pythonAnacondapythonEVCapturepythonEvernote_6.21.3.2048.exepythonNotepad++pythonpycharm-community-2020.1.3.exepythonpycharm2020pythonpyecharts-assets-masterpythonpyecharts-gallery-masterpythonSublime 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 Pathpath = r’D:pythonpycharm2020program’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 Pathpath = r’D:pythonpycharm2020program’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 Pathdef 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_filespath = 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 Pathp = Path(r’D:pythonpycharm2020programtest’)p.mkdir()p.rmdir()

from pathlib import Pathp = Path(r’D:pythontest1test2test3’)p.mkdir(parents=True) # If parents is true, any missing parents of this path are created as neededp.rmdir() # 刪除的是test3文件夾

from pathlib import Pathp = Path(r’D:pythontest1test2test3’)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 Pathp = 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 編程
相關文章:
主站蜘蛛池模板: 泵阀展|阀门展|水泵展|流体机械展 -2025上海国际泵管阀展览会flowtech china | 桁架机器人_桁架机械手_上下料机械手_数控车床机械手-苏州清智科技装备制造有限公司 | 高压包-点火器-高压发生器-点火变压器-江苏天网 | 电抗器-能曼电气-电抗器专业制造商 | POS机办理_个人pos机免费领取-银联pos机申请首页 | 苗木价格-苗木批发-沭阳苗木基地-沭阳花木-长之鸿园林苗木场 | 无刷电机_直流无刷电机_行星减速机-佛山市藤尺机电设备有限公司 无菌检查集菌仪,微生物限度仪器-苏州长留仪器百科 | 动库网动库商城-体育用品专卖店:羽毛球,乒乓球拍,网球,户外装备,运动鞋,运动包,运动服饰专卖店-正品运动品网上商城动库商城网 - 动库商城 | 整车VOC采样环境舱-甲醛VOC预处理舱-多舱法VOC检测环境仓-上海科绿特科技仪器有限公司 | 网站建设-高端品牌网站设计制作一站式定制_杭州APP/微信小程序开发运营-鼎易科技 | 液压升降货梯_导轨式升降货梯厂家_升降货梯厂家-河南东圣升降设备有限公司 | 恒温振荡混匀器-微孔板振荡器厂家-多管涡旋混匀器厂家-合肥艾本森(www.17world.net) | 橡胶接头_橡胶软接头_套管伸缩器_管道伸缩器厂家-巩义市远大供水材料有限公司 | 卸料器-卸灰阀-卸料阀-瑞安市天蓝环保设备有限公司 | 炭黑吸油计_测试仪,单颗粒子硬度仪_ASTM标准炭黑自销-上海贺纳斯仪器仪表有限公司(HITEC中国办事处) | 丹佛斯变频器-丹佛斯压力开关-变送器-广州市风华机电设备有限公司 | sfp光模块,高速万兆光模块工厂-性价比更高的光纤模块制造商-武汉恒泰通 | 步进_伺服_行星减速机,微型直流电机,大功率直流电机-淄博冠意传动机械 | 民用音响-拉杆音响-家用音响-ktv专用音响-万昌科技 | 砂石生产线_石料生产线设备_制砂生产线设备价格_生产厂家-河南中誉鼎力智能装备有限公司 | 东莞市天进机械有限公司-钉箱机-粘箱机-糊箱机-打钉机认准东莞天进机械-厂家直供更放心! | 安徽泰科检测科技有限公司【官方网站】 | 直线模组_滚珠丝杆滑台_模组滑台厂家_万里疆科技 | 武汉高温老化房,恒温恒湿试验箱,冷热冲击试验箱-武汉安德信检测设备有限公司 | 广州/东莞小字符喷码机-热转印打码机-喷码机厂家-广州瑞润科技 | 鼓风干燥箱_真空烘箱_高温干燥箱_恒温培养箱-上海笃特科学仪器 | 热处理温控箱,热处理控制箱厂家-吴江市兴达电热设备厂 | 钢木实验台-全钢实验台-化验室通风柜-实验室装修厂家-杭州博扬实验设备 | 出国劳务公司_正规派遣公司[严海]| 氨水-液氨-工业氨水-氨水生产厂家-辽宁顺程化工 | 杭州网络公司_百度SEO优化-外贸网络推广_抖音小程序开发-杭州乐软科技有限公司 | 纸箱抗压机,拉力机,脂肪测定仪,定氮仪-山东德瑞克仪器有限公司 | 磁力加热搅拌器-多工位|大功率|数显恒温磁力搅拌器-司乐仪器官网 | 检验科改造施工_DSA手术室净化_导管室装修_成都特殊科室建设厂家_医疗净化工程公司_四川华锐 | 钢衬四氟管道_钢衬四氟直管_聚四氟乙烯衬里管件_聚四氟乙烯衬里管道-沧州汇霖管道科技有限公司 | 智能垃圾箱|垃圾房|垃圾分类亭|垃圾分类箱专业生产厂家定做-宿迁市传宇环保设备有限公司 | 热镀锌槽钢|角钢|工字钢|圆钢|H型钢|扁钢|花纹板-天津千百顺钢铁贸易有限公司 | 锂电池生产厂家-电动自行车航模无人机锂电池定制-世豹新能源 | 除湿机|工业除湿机|抽湿器|大型地下室车间仓库吊顶防爆除湿机|抽湿烘干房|新风除湿机|调温/降温除湿机|恒温恒湿机|加湿机-杭州川田电器有限公司 | 淬火设备-钎焊机-熔炼炉-中频炉-锻造炉-感应加热电源-退火机-热处理设备-优造节能 | 防爆大气采样器-防爆粉尘采样器-金属粉尘及其化合物采样器-首页|盐城银河科技有限公司 |