路径操作模块
3.4 版本之前os.path 模块from os import pathfrom os import pathp = path.join("/etc","sysconfig","network")
print(1,type(p),p)print(2,path.exists(p))print(3,path.split(p)) # (head,tail)print(4,path.abspath(".")) #当前目录p = path.join("F:/",p,"test.txt")print(5,path.dirname(p)) #路径名print(6,path.basename(p))# 文件名print(7,path.splitdrive(p))#(盘符跟路径的元组)1 <class 'str'> /etc\sysconfig\network
2 False3 ('/etc\sysconfig', 'network')4 D:\Learning\project\exercise5 F:/etc\sysconfig\network6 test.txt7 ('F:', '/etc\sysconfig\network\test.txt')p1 = path.abspath(file)
print(p1,path.basename(p1))while p1 != path.dirname(p1): # 如果p1 != p1 的路径名,继续循环p1 = path.dirname(p1)print(p1,path.basename(p1))D:\Learning\project\exercise\testfunc.py testfunc.py
D:\Learning\project\exercise exerciseD:\Learning\project projectD:\Learning LearningD:\3.4版本开始
建议使用pathlib模块,提供Path对象来操作。包括目录和文件from pathlib import Pathp = Path() #当前目录p = Path("a","b","c/d")# 当前目录下的a/b/c/dp = Path("/etc")# 根下的etc目录绝对路径:p.absolute()路径拼接和分解操作符 “/ ”Path对象 / Path对象
Path对象 / 字符串 或者 字符串 / Path对象分解
parts 属性,可以返回路径中的每一个部分 p1 = a\b\c\d\e\fprint(p1.parts)('a', 'b', 'c', 'd', 'e', 'f')
jointpathjointpath(*other)连接多个字符串到Path对象中p = Path("a/b/c")print(1,p)p1 = p / "d" / "e" / "f"print(2,p1)print(3,p1.parts)p3 = p.joinpath("a","b","c",p,p / "d",Path("http"))print(4,p3)print(5,p.joinpath("etc","init.d",Path("http")))print(6,p)1 a\b\c
2 a\b\c\d\e\f3 ('a', 'b', 'c', 'd', 'e', 'f')4 a\b\c\a\b\c\a\b\c\a\b\c\d\http5 a\b\c\etc\init.d\http6 a\b\c获取路径
str 获取路径字符串bytes 获取路径字符串的bytesp4 = Path("etc")s = str(p4)b = bytes(p4)print(s,b)etc b'etc'
全局方法
cwd() 返回当前工作目录home() 返回当前家目录判断方法p = Path("/etc/mysqlinstall/mysql.tar.gz")print(p.is_dir()) #是否是目录,目录存在返回Trueprint(p.is_file()) #是否是普通文件,文件存在返回Trueprint(p.is_symlink())# 是否是软链接print(p.is_socket()) #是否是socket文件print(p.is_block_device())#是否是块设备print(p.is_char_device())# 是否是字符设备print(p.is_absolute()) #是否是绝对路径print(p.resolve()) #返回一个新的路径,这个路径就是当前Path对象的绝对路径,如果是软链接则直接被解析print(p.exists()) #目录或文件是否存在False
FalseFalseFalseFalseFalseFalseD:\etc\mysqlinstall\mysql.tar.gzFalsermdir() 删除空目录。没有提供给判断目录为空的方法
目录不为空时,弹出OS Error(OSError: [WinError 145] 目录不是空的。: 'F:\newfile')touch(mode=0o666,exist_ok = True)创建一个文件
as_uri() 将路径返回成URI,例如“file:///etc/passwd”
print(Path("F:/file/a/b/c/d").as_uri())file:///F:/file/a/b/c/d
mkdir(mode=0o777,parents=False,exist_ok=False)
parents,是否创建父目录,True等同于mkdir -p; False时,父目录不存在,则抛出FileNotFoundErrorexist_ok参数,在3.5版本加入。False时,路径存在,抛出FileExistsError;True时,Error被忽略iterdir() 迭代当前目录 (没有递归,当前目录下的文件)
from pathlib import Pathp = Path("a/b/c/d/")print(p.iterdir()) # 返回一个生成器对象<generator object Path.iterdir at 0x0000020C28100830>
from pathlib import Path
p = Path("F:/newfile")for y in p.parents[len(p.parents) - 1].iterdir():print(y, end="\t")if y.isdir():flag = Falsefor in y.iterdir():flag = Truebreakprint("dir","not empty" if flag else "empty",sep="\t")elif y.is_file():print("file")else:print("other file")py12-湖北-胡炎林 2018/9/9 17:36:46
通配符
glob(pattern) 通配给定的模式rglob(pattern)通配给定的模式,递归目录都返回一个生成器list(p.glob("test*")) #返回当前目录对象下的test开头的文件list(p.glob("*/.py"))#递归所有目录,等同rglobg = p.rglob("*.py") #生成器next(g)匹配
match(pattern)模式匹配,成功返回TruePath("a/b/.py").match("*.py") #TruePath("a/b/c.py").match("b/c.py") #TruePath("a/b/c.py").match("*/.py") #Truestat() 相当于stat命令
lstat() 同 stat() 但如果是符号链接,则显示符号链接本身的文件信息from pathlib import Pathimport osp = Path("F:/test.ini")a = p.stat()print(a)b = os.stat(p)print(b)os.stat_result(st_mode=33206, st_ino=1970324836978426, st_dev=3024289130, st_nlink=1, st_uid=0, st_gid=0, st_size=209, st_atime=1536146816, st_mtime=1536146886, st_ctime=1536130661)
os.stat_result(st_mode=33206, st_ino=1970324836978426, st_dev=3024289130, st_nlink=1, st_uid=0, st_gid=0, st_size=209, st_atime=1536146816, st_mtime=1536146886, st_ctime=1536130661)文件操作
Path.open(mode="r",buffer=-1,encoding=None,errors=None,newline=None)使用方法类似内内建函数open。返回一个文件对象,3.5增加的新函数Path.read_bytes()
以“rb”读取路径文件,并返回二进制流。 Open the file in text mode, read it, and close the file.Path.read_text(encoding=None,error=None)
以“rt”读取路径对应文件,返回文本Path.write_bytes(data)
以“wb”方式写入数据到路径对应文件Path.write_text(data)
以“wt”方式写入数据到路径对应文件open模式进行文件copy
src = "F:/test.txt"dest = "F:/newfile/test1"def copy_file(src,dest):with open(src) as f1:with open(dest,"w+") as f2:f2.write(f1.read())copy_file(src,dest)
父目录
partent 目录的逻辑父目录parents 父目录序列,索引0是直接的父p5 = Path("a/b/c/d/e")print(1,p5.parent.parent)for x in p5.parents:print(2,x)1 a\b\c
2 a\b\c\d2 a\b\c2 a\b2 a2 .目录组成部分:
name、stem、suffix、suffixes、with_suffix(suffix)、with_name(name)name 目录的最后一个部分suffix 目录中最后一个部分的扩展名stem 目录最后一个部分,没有后缀suffixes 返回多个扩展名列表with_suffix(suffix)有扩展名则替换,无则补充扩展名with_name(name)替换目录最后一个部分并返回一个新的路径from pathlib import Pathp = Path("/etc/mysqlinstall/mysql.tar.gz")
print(1,p.name)print(2,p.suffix)print(3,p.suffixes)# 返回多个扩展名列表print(4,p.stem)print(5,p.with_suffix(".png"))print(6,p.with_name("mysql.tgz"))p = Path("README")print(7,p.with_suffix(".txt"))print(8,p.with_suffix(".txt").suffixes)1 mysql.tar.gz
2 .gz3 ['.tar', '.gz']4 mysql.tar5 \etc\mysqlinstall\mysql.tar.png6 \etc\mysqlinstall\mysql.tgz7 README.txt8 ['.txt']
精彩评论