shutil 模块

基本概念

  • shutil 可以简单地理解为 sh + utilshell 工具 的意思
  • 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
  • 文件内容,所有者和组不受影响
  • srcdst 是以字符串形式给出的路径名称

案例

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")

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值