学习笔记(72):Python入门教程-shutil模块l文件copy&打包压缩

立即学习:https://edu.csdn.net/course/play/24459/296369?utm_source=blogtoedu

shutil模块:

shutil.copyfileobj(fsrc,fdst[,length]):将文件内容拷贝到另一个文件中,需要先把文件打开

shutil.copyfileobj(open("demo.py"),open("demo2.py","w"))

shutil.copyfile(src,dst):拷贝文件,不需要打开

shutil.copymode(src,dst):仅拷贝权限,内容、组、用户均不变

shutil.copystat(src,dst):仅拷贝状态信息,包括mode、bits、atime、mtime、flags

shutil.copy(src,dst):拷贝文件和权限

shutil.copy2(src,dst):拷贝文件和状态信息

shutil.ignore_patterns(*pattern)

shutil.copytree(src,dst,symlinks=False,ignore=None):递归的去拷贝文件夹

shutil.rmtree(path[,ignore_errors[,onerror]]):递归的去删除文件

shutil.move(src,dst):递归的去移动文件,它类似mv命令,其实就是重命名

shutil.make_archive(base_name.format,..):创建压缩包并返回文件路径,例如:zip、tar

base_name:压缩包文件名或路径

format:压缩包种类,zip、tar、bztar、gztar

root_dir:要压缩的文件夹路径(默认当前目录)

owner:用户,默认当前用户

group:组,默认当前组

logger:用于记录日志,通常是logging.Logger对象

 

shutil对压缩包的处理是调用ZipFile 和 TarFile两个模块来进行的

zipfile压缩&解压缩:

import zipfile

#压缩

z = zipfile.ZipFile('laxi.zip','w')

z.write('a.log')

z.write('data.data')

z.close()

#解压

z = zipfile.ZipFile('laxi.zip','r')

z.extractall(path='.')

z.close()

 

tarfile压缩&解压缩

import tarfile

#压缩

t = tarfile.open('/tmp/egon.tar','w')

t.add('/test1/a.py',arcname='a.bak')

t.add('/test1/b.py',arcname='b.bak')

t.close()

#解压

t = tarfile.open('/tmp/egon.tar','r')

t.extractall('/egon')

t.close()

 

import zipfile
import os

z = zipfile.ZipFile("test_compress.zip",'w')
filelist = []
print(os.walk("pytest/venv"))
for root_dir,dirs,files in os.walk("pytest"):
    for filename in files:
        filelist.append(os.path.join(root_dir,filename))
for i in filelist:
    print(i)
    z.write(i)

z.close()

z = zipfile.ZipFile('test_compress.zip','r')
z.extractall(path='User/Downloads')
z.close()

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值