python 文件管理库 Path 解析(详细基础)
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
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!