总结面向对象文件系统路径操作模块purepaths:纯路径操作,不提供I/O操作具体路径:路径计算操作+I/O操作常用操作1.path的属性列出所有父目录和parent目录、文件名或目录名、文件前缀、文件后缀等...frompathlibimportPathp=Path('./test/filename.text')p.parents#所有父目录>>WindowsPath.parentsp.parent#父目录>>testp.name#文件名或目录名>>filename.textp.stem#文件前缀>>filenamep.suffix#文件后缀>>.textp.is_dir()#文件夹判断>>Falsep.is_file()#文件判断>>Truep.exists()#路径是否存在>>Truep.stat()#获取路径属性>>os.stat_result(st_mode=16895,st_ino=7036874417855445,st_dev=2287178555,st_nlink=1,st_uid=0,st_gid=0,st_size=0,st_atime=1576075587,st_mtime=1576075562,st_ctime=1576075197)2.路径操作创建文件夹,路径连接,w写入文件、读取文件、遍历子路径等...frompathlibimportPath#createfolderbase_path=Path('dir/child_dir')base_path.mkdir(exist_ok=True,parents=True)#路径连接file_path=base_path/Path('file.text')#创建文件file_path.touch(exist_ok=True)#writefilewithfile_path.open(mode='w',encoding='utf-8')asf:f.write('HelloWorld')#readthefilewithfile_path.open(mode='r')asf:print(f.read())#遍历子路径forpathinp.iterdir():print(path)#递归遍历子路径(常规)foriteminbase_path.rglob('*.text'):print(item)#移动文件夹new_path=base_path/Path('new_file.text')file_path.replace(new_path)#删除文件new_path.unlink()#删除文件夹(必须为空)new_path.parent.rmdir()附录os和os.pathpathlib说明os.path.abspath()Path.resolve()获取path的绝对路径os。path.chmod()Path.chmod()更改路径的权限os.path.mkdir()Path.mkdir()创建文件夹os.path.rename()Path.rename()路径重命名os.path.replace()Path.replace()路径重命名(如果有新路径则替换)os.path.remove(),os.unlink()Path.unlink()删除路径os.path.cwd()Path.cwd()当前工作路径(当前工作目录)os.path.exists()Path.exists()path存在os.path.expanduser()Path.expanduser()path添加当前用户os.path.isdir()Path.is_dir()isfolderos.path.isfile()Path.is_file()is是否文件os.path.islink()Path.is_symlink()是软链接()是同一个文件os.path.isabs()PurePath.is_absolute()是否是绝对路径os.path.join()PurePath.joinpath()路径加入操作os.path.dirname()PurePath.parentprefixpathos.path.basename()PurePath.name路径名os.path.splitext()PurePath.suffix路径后缀参考https://docs.python.org/zh-cn/3/library/pathlib.htmlhttps://xin053.github.io/2016/07/03/pathlib%E8%B7%AF%E5%BE%84%E5%BA%93%E4%BD%BF%E7%94%A8%E8%AF%A6%E8%A7%A3/
