python 文件管理库 Path 解析(详细基础)

news2026/4/5 17:17:18
1 Path库能做什么Path库是python常见的文件操作库以对象形式操作文件路径可以进行以下操作文件路径的拼接example:test / Your_path / files文件地址的提取提取名称、后缀、全程......层级关系访问查询文件是否存在创建目录.............基本上文件操作都够用的实用库2 Path 与 os 库的优势 可选了解文件操作库os的可以查看不了解建议略过from pathlib import Pathimport osdef get_base_name_vs_os(input_file_path:str):获取当前py文件的完整名称、不带后缀名称、后缀:return:fpath_os input_file_pathfpath_path Path(input_file_path)#u can debug this function and try to input- type(fpath_path) in ur IDE-debug window,u can see class pathlib.WindowsPathprint(fos method: {os.path.basename(fpath_os)}, {os.path.basename(os.path.splitext(fpath_os)[0])}, {os.path.splitext(fpath_os)[-1]})print(fPath method: {fpath_path.name}, {fpath_path.stem}, {fpath_path.suffix})returnif __name__ __main__:get_base_name_vs_os(ryour_file_path_like_C:\window)优势Path库相比os库有更全的封装接口能够快速且便携地获取想要的文件地址同样的实现步骤可能需要好几层os操作对象为Object即面向对象可以很方便调用类方法而os需要调用os库相对来说繁琐一些劣势虽然在很多方面完胜os但本质是不可哈希的类型——object类类型在写接口兼容、调用路径时需要注意。其他兼容性问题。3 Path库常用操作3.1 初始化路径想初始化Path对象路径很简单和其他类对象一样只需要Path(your_path)即可获得对应的路径对象。def init_path():input_path Path(ryour_input_path_test.py)#直接通过Path 初始化print(input_path)return input_path除了直接通过单一变量初始化路径还能通过以下示例进行初始化input_path Path(rC:\\,Windows,your_dir) #构造 c盘window/your_dir的文件路径可以传入多个路径返回他们按顺序构造的路径input_path input_path / hello_world.py3.2 获取文件地址文件名称【带后缀、不带后缀】及后缀假设已经获取了文件对象的变量为input_path Path(your_path)文件名称(完整带后缀)用input_path.name即可 ,返回带后缀的文件名称【依旧是Path对象】文件名称(不带后缀)用input_path.stem即可stem有茎的意思假设文件路径像一朵花地上的花就包含了花朵和根茎少了花朵部分根茎也可以被认为是不带后缀花朵的了。文件名称(后缀)用input_path.suffix即可 suffix翻译过来就是后缀返回文件后缀【str】但是这里要注意如果有多个后缀如library.tar.gz, 则会返回最后一个后缀如果想要获取n个后缀请使用suffixes。def get_path_name_stem_suffix(input_path:Path):name input_path.namename_without_suffix input_path.stemsuffix input_path.suffixprint(f\n u get it- name:{name} ; stem: {name_without_suffix} ; suffix:{suffix}\n)return官方示例namePurePosixPath(my/library/setup.py).namePureWindowsPath(//some/share/setup.py).namePureWindowsPath(//some/share).namestemPurePosixPath(my/library.tar.gz).stemPurePosixPath(my/library.tar).stemPurePosixPath(my/library).stemsuffixPurePosixPath(my/library/setup.py).suffixPurePosixPath(my/library.tar.gz).suffixPurePosixPath(my/library).suffix3.3 获取路径状态当我们对路径进行操作时需要判断当前路径所处的位置、是否为文件、是否为文件夹等。假设已经获取了文件对象的变量为input_path Path(your_path)是否存在返回 bool: (True or False)exist input_path.exists()是否是文件夹返回 bool: (True or False)whether_dir input_path.is_dir()是否是文件返回 bool: (True or False)whether_file input_path.is_file()常用状态总def get_path_status(input_path:Path):exist input_path.exists()whether_dir input_path.is_dir()whether_file input_path.is_file()print(f\n file exist status:{exist}, dir :{whether_dir}, file:{whether_file}\n)return3.4 获取当前/父文件夹​ 使用os库时对父文件夹的控制相对较为繁琐而Path对于文件夹层级的管理比较简单。假设我们有一个路径为“C:\Windows\Learning\pycharm\hello_world.py”那他的当前路径为pycharm父路径为Learning,可以使用以下操作获取def get_father_and_local_dir(input_path:Path):local_dir input_path.parentall_father_dir input_path.parents #返回的是 Path.parents类似于可迭代对象如果想要直接看所有结构就list化for father_dir,idx in enumerate(all_father_dir):output f(father_{idx}){father_dir}print(output,end) #迭代参考可以自行debug体会一下print() #纯美化用all_father_dirs list(input_path.parents) # list(Path.parents), u can easily get valuefather_1_dir str(input_path.parents[1]) # get idx1[start in 0 index] parents and str the valueprint(flocal_dir:{local_dir}, father_1_dir:{father_1_dir} ,all_father_dir:{all_father_dirs} \n)PS通常获取当前目录使用.parent就够用了他同样返回当前父文件夹的Path对象获取前n个父级文件夹路径就使用.parents就好但注意他返回的是可迭代对象不能直接使用需要直接使用就套list返回的可迭代对象从0开始也就是说input_path.parents[0]local_dir input_path.parent3.5 路径拼接在上文初始化时我们提及了其中一种路径拼接的方式调用初始化函数input_path Path(rC:\\,Windows,your_dir) #构造 c盘window/your_dir的文件路径可以传入多个路径返回他们按顺序构造的路径input_path input_path / hello_world.py除此之外还有函数方式进行拼接def join_path(input_path:Path,sub_paths(hello,world)):from copy import deepcopyexample_1,example_2 deepcopy(input_path), deepcopy(input_path)for sub_path in sub_paths:example_1 example_1 / sub_path #两种路径拼接方式等价个人建议使用 重载的”/“方便简洁example_2 example_2.joinpath(sub_path)print(f{**50}\nf{example_1}; {example_2}; f\n{**50}\n)3.6 确保文件路径存在创建路径def make_sure_dir_exist(input_path:Path):input_path.mkdir(parentsTrue,exist_okTrue) #相对固定类似于模板父文件夹自动创建True文件夹存在不会重复创建 True使用mkdir这个接口即可一般来说都会使用这样的配置parents: 父文件夹是否需要创建exist_ok: 路径已存在文件夹的情况是否处理Create a new directory at this given path. Ifmodeis given, it is combined with the process’umaskvalue to determine the file mode and access flags. If the path already exists, FileExistsError is raised.Ifparentsis true, any missing parents of this path are created as needed; they are created with the default permissions without takingmodeinto account (mimicking the POSIXmkdir -pcommand).Ifparentsis false (the default), a missing parent raises FileNotFoundError.Ifexist_okis false (the default), FileExistsError is raised if the target directory already exists.Ifexist_okis true, FileExistsError exceptions will be ignored (same behavior as the POSIXmkdir -pcommand), but only if the last path component is not an existing non-directory file.Changed in version 3.5:Theexist_okparameter was added.3.7 计算文件路径间的差异进阶接口介绍def cal_path_diff(path_1:Path, path_2:PathPath.cwd()):计算两个路径间的相对路径差:param path_1: 子集路径【范围更广】:param path_2: 父集路径【范围更小】这种方式仅适用于父集和子集之间无依附关系则会报错try:diff path_1.relative_to(path_2)diff_2 path_2.relative_to(path_1)print(str(diff), \n)# print(str(diff_2),\n) #如果path_2是path_1的父集就会error【反之同理】只能从子集计算父集的差距路径except Exception as e:raise e官方参考 p PurePosixPath(/etc/passwd) p.relative_to(/)PurePosixPath(etc/passwd) p.relative_to(/etc)PurePosixPath(passwd) p.relative_to(/usr)Traceback (most recent call last):File stdin, line 1, in moduleFile pathlib.py, line 694, in relative_to.format(str(self), str(formatted)))ValueError: /etc/passwd is not in the subpath of /usr OR one path is relative and the other absolute3.8 获取当前目录下 指定后缀文件略进阶def find_files(input_path:Path, files_suffix:str.jpg):找文件下的文件通过通配符查找:param input_path: 输入路径:param files_suffix: 匹配的后缀可以自己换一下后缀或者不要后缀换一下路径debug体会一下还能配合列表推导式还算实用但我觉得os.walk对文件遍历好一些specimen_1 input_path.glob(f*{files_suffix}) #不递归进入specimen_2 input_path.glob(f**/*{files_suffix}) #递归进入same to : path.rglob(*.files_suffix)print(fspecimen_1:{list(specimen_1)} \n specimen_2:{list(specimen_2)}\n)真要大面积遍历文件的话我建议用os.walk会好一些【参考 chapter2】4.参考文档official_path_doc最常使用的基本上是上面这些了还有什么需要的再查再找就好了基础解析到这里应该够用了bey~感谢你看到这里希望这篇文章能给你带来一些帮助喜欢的话帮我点个赞吧。5.codeMain_testfrom pathlib import Pathdef init_path():# input_path Path(rE:\Learning\test.py)input_path Path(rE:\\,rLearning,os_vs_path.py)print(input_path)return input_pathdef get_path_name_stem_suffix(input_path:Path):name input_path.namename_without_suffix input_path.stemsuffix input_path.suffixprint(fu get it- name:{name} ; stem: {name_without_suffix} ; suffix:{suffix}\n)returndef get_path_status(input_path:Path):exist input_path.exists()whether_dir input_path.is_dir()whether_file input_path.is_file()print(ffile exist status:{exist}, dir :{whether_dir}, file:{whether_file}\n)returndef get_father_and_local_dir(input_path:Path):local_dir input_path.parentall_father_dir input_path.parents #返回的是 Path.parents类似于迭代器如果想要直接看所有结构就list化for father_dir,idx in enumerate(all_father_dir):output f(father_{idx}){father_dir}print(output,end) #迭代参考可以自行debug体会一下print() #纯美化用all_father_dirs list(input_path.parents) # list(Path.parents), u can easily get valuefather_1_dir str(input_path.parents[1]) # get idx1[start in 0 index] parents and str the valueprint(flocal_dir:{local_dir}, father_1_dir:{father_1_dir} ,all_father_dir:{all_father_dirs} \n)def join_path(input_path:Path,sub_paths(hello,world)):from copy import deepcopyexample_1,example_2 deepcopy(input_path), deepcopy(input_path)for sub_path in sub_paths:example_1 example_1 / sub_path #两种路径拼接方式等价个人建议使用 重载的”/“方便简洁example_2 example_2.joinpath(sub_path)print(f{**50}\nf{example_1}; {example_2}; f\n{**50}\n)def make_sure_dir_exist(input_path:Path):input_path.mkdir(parentsTrue,exist_okTrue) #相对固定类似于模板父文件夹自动创建True文件夹存在不会重复创建 Truedef cal_path_diff(path_1:Path, path_2:PathPath.cwd()):计算两个路径间的相对路径差:param path_1: 子集路径【范围更广】:param path_2: 父集路径【范围更小】这种方式仅适用于父集和子集之间无依附关系则会报错try:diff path_1.relative_to(path_2)diff_2 path_2.relative_to(path_1)print(str(diff), \n)# print(str(diff_2),\n) #如果path_2是path_1的父集就会error【反之同理】只能从子集计算父集的差距路径except Exception as e:raise edef find_files(input_path:Path, files_suffix:str.jpg):找文件下的文件通过通配符查找:param input_path: 输入路径:param files_suffix: 匹配的后缀可以自己换一下后缀或者不要后缀换一下路径debug体会一下specimen_1 input_path.glob(f*{files_suffix}) #不递归进入specimen_2 input_path.glob(f**/*{files_suffix}) #递归进入same to : path.rglob(*.files_suffix)print(fspecimen_1:{list(specimen_1)} \n specimen_2:{list(specimen_2)}\n)if __name__ __main__:t_path init_path()get_path_name_stem_suffix(t_path)get_path_status(input_patht_path)get_father_and_local_dir(t_path)join_path(t_path)find_files(t_path)cal_path_diff(t_path,Path(C:\\Windows)) #记得删掉后面路径再试一次就不会报错了Os Vs Path:from pathlib import Pathimport osdef get_base_name_vs_os(input_file_path:str):获取当前py文件的完整名称、不带后缀名称、后缀:return:fpath_os input_file_pathfpath_path Path(input_file_path)#u can debug this function and try to input- type(fpath_path) in ur IDE-debug window,u can see class pathlib.WindowsPathprint(fos method: {os.path.basename(fpath_os)}, {os.path.basename(os.path.splitext(fpath_os)[0])}, {os.path.splitext(fpath_os)[-1]})print(fPath method: {fpath_path.name}, {fpath_path.stem}, {fpath_path.suffix})returnif __name__ __main__:get_base_name_vs_os(rE:\Learning\os_vs_path.py)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2486384.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…