路径操作模块
3.4 版本之前
os.path 模块
- from os import path
- from os import path
- p = 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 False
- 3 ('/etc\sysconfig', 'network')
- 4 D:\Learning\project\exercise
- 5 F:/etc\sysconfig\network
- 6 test.txt
- 7 ('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 exercise
- D:\Learning\project project
- D:\Learning Learning
- D:\
3.4 版本开始
建议使用 pathlib 模块, 提供 Path 对象来操作. 包括目录和文件
- from pathlib import Path
- p = Path() #当前目录
- p = Path("a","b","c/d")# 当前目录下的 a/b/c/d
- p = Path("/etc")# 根下的 etc 目录
绝对路径:
p.absolute()
路径拼接和分解
操作符 "/"
Path 对象 / Path 对象
Path 对象 / 字符串 或者 字符串 / Path 对象
分解
parts 属性, 可以返回路径中的每一个部分
- p1 = a\b\c\d\e\f
- print(p1.parts)
- ('a', 'b', 'c', 'd', 'e', 'f')
- jointpath
jointpath(*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\f
- 3 ('a', 'b', 'c', 'd', 'e', 'f')
- 4 a\b\c\a\b\c\a\b\c\a\b\c\d\http
- 5 a\b\c\etc\init.d\http
- 6 a\b\c
获取路径
str 获取路径字符串
bytes 获取路径字符串的 bytes
- p4 = 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()) #是否是目录, 目录存在返回 True
- print(p.is_file()) #是否是普通文件, 文件存在返回 True
- print(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
- False
- False
- False
- False
- False
- False
- D:\etc\mysqlinstall\mysql.tar.gz
- False
rmdir() 删除空目录. 没有提供给判断目录为空的方法
目录不为空时, 弹出 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 时, 父目录不存在, 则抛出 FileNotFoundError
exist_ok 参数, 在 3.5 版本加入. False 时, 路径存在, 抛出 FileExistsError;True 时, Error 被忽略
iterdir() 迭代当前目录 (没有递归, 当前目录下的文件)
- from pathlib import Path
- p = 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 = False
- for in y.iterdir():
- flag = True
- break
- print("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"))# 递归所有目录, 等同 rglob
- g = p.rglob("*.py") #生成器
- next(g)
匹配
match(pattern)
模式匹配, 成功返回 True
- Path("a/b/.py").match("*.py") #True
- Path("a/b/c.py").match("b/c.py") #True
- Path("a/b/c.py").match("*/.py") #True
stat() 相当于 stat 命令
lstat() 同 stat() 但如果是符号链接, 则显示符号链接本身的文件信息
- from pathlib import Path
- import os
- p = 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\d
- 2 a\b\c
- 2 a\b
- 2 a
- 2 .
目录组成部分:
name,stem,suffix,suffixes,with_suffix(suffix),with_name(name)
name 目录的最后一个部分
suffix 目录中最后一个部分的扩展名
stem 目录最后一个部分, 没有后缀
suffixes 返回多个扩展名列表
with_suffix(suffix) 有扩展名则替换, 无则补充扩展名
with_name(name) 替换目录最后一个部分并返回一个新的路径
- from pathlib import Path
- p = 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 .gz
- 3 ['.tar', '.gz']
- 4 mysql.tar
- 5 \etc\mysqlinstall\mysql.tar.png
- 6 \etc\mysqlinstall\mysql.tgz
- 7 README.txt
- 8 ['.txt']
来源: http://www.bubuko.com/infodetail-2761626.html