基本概念
- shutil 可以简单地理解为 sh + util,shell 工具 的意思
- shutil 模块是对 os 模块的补充,主要针对文件的 拷贝、删除、移动、压缩和解压 操作
shutil 模块的主要方法
复制和移动
shutil.copyfileobj(fsrc, fdst)
- 将文件的对象 fsrc 的内容复制到文件的对象 fdst
案例
import shutil
# 复制
# 1. shutil.copyfileobj(源文件管家,目标文件管家):只能复制文件的内容,无法复制权限
fr=open("/etc/hosts", mode="r")
fw=open("/opt/myhosts", mode="w")
shutil.copyfileobj(fr, fw)
fr.close()
fw.close()
shutil.copyfile(src, dst)
- 将名为 src 的文件的内容复制到名为 dst 的文件
案例
import shutil
# 2. shutil.copyfile(源文件路径, 目标文件路径):只能复制文件的内容,无法复制权限
shutil.copyfile("/usr/bin/ls", "/opt/myls")
shutil.copy(src, dst)
将文件 src 复制到文件或目录 dst,包括权限
案例
import shutil # 导入模块(如果已经导入,则不需要再次导入)
# 3. shutil.copy(源文件路径, 目标文件路径):既能复制文件的内容,也能复制权限
shutil.copy("/usr/bin/ls", "/opt/myls2")
shutil.move(src, dst)
- 递归地将文件或目录(src)移动到另一个位置(dst),并返回目标
案例
import shutil # 导入模块(如果已经导入,则不需要再次导入)
shutil.move("/opt/myls2", "/opt/myls3")
目录操作
shutil.copytree(src, dst)
- 递归地复制以 src 为根的整个目录树,返回目标目录。由 dst 命名的目标目录不能已经存在
案例
import shutil # 导入模块(如果已经导入,则不需要再次导入)
shutil.copytree('/etc/security', '/opt/security') # 使用copytree()时,需要指定一个不存在的目录,否则报错
shutil.rmtree(path)
- 删除整个目录树; 路径 必须指向目录, 空目录或者非空目录都可使用
import shutil # 导入模块(如果已经导入,则不需要再次导入)
shutil.rmtree("/opt/security")
权限管理
shutil.copymode(src, dst)
- 将权限位从 src 复制到 dst
- 文件内容,所有者和组不受影响
- src 和 dst 是以字符串形式给出的路径名称
案例
import shutil # 导入模块(如果已经导入,则不需要再次导入)
# 使用shutil模块的copymode()功能【只拷贝权限】
shutil.copymode("/usr/bin/ls", "/opt/myhosts")
shutil.chown(path, user=None, group=None)
- 更改给定 路径 的所有者 用户 和 组
案例
import shutil # 导入模块(如果已经导入,则不需要再次导入)
shutil.chown("/opt/myhosts",user="cuihua",group="cuihua")