Python中文件copy模块shutil

高级的 文件、文件夹、压缩包 处理模块

python 复制代码
shutil.copyfileobj(fsrc, fdst[, length])

将文件内容拷贝到另一个文件中

python 复制代码
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
shutil.copyfile(src, dst)

拷贝文件

python 复制代码
shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
shutil.copymode(src, dst)

仅拷贝权限。内容、组、用户均不变

python 复制代码
shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
shutil.copystat(src, dst)

仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

python 复制代码
shutil.copystat('f1.log', 'f2.log') #目标文件必须存在
shutil.copy(src, dst)

拷贝文件和权限

python 复制代码
import shutil
shutil.copy('f1.log', 'f2.log')
shutil.copy2(src, dst)

拷贝文件和状态信息

python 复制代码
import shutil
shutil.copy2('f1.log', 'f2.log')
shutil.ignore_patterns(*patterns)

shutil.copytree(src, dst, symlinks=False, ignore=None)

递归的去拷贝文件夹

python 复制代码
import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
shutil.rmtree(path[, ignore_errors[, onerror]])

递归的去删除文件

python 复制代码
import shutil
shutil.rmtree('folder1')
shutil.move(src, dst)

递归的去移动文件,它类似mv命令,其实就是重命名。

python 复制代码
import shutil
shutil.move('folder1', 'folder3')
shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

可选参数如下:

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,

如 data_bak =>保存至当前路径

如:/tmp/data_bak =>保存至/tmp/

  • format: 压缩包种类,"zip", "tar", "bztar","gztar"
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
python 复制代码
#将 /data 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
#将 /data下的文件打包放置 /tmp/目录
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

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

zipfile压缩&解压缩

python 复制代码
import zipfile
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()

tarfile压缩&解压缩

python 复制代码
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()
相关推荐
奈斯。zs10 分钟前
yjs08——矩阵、数组的运算
人工智能·python·线性代数·矩阵·numpy
Melody205010 分钟前
tensorflow-dataset 内网下载 指定目录
人工智能·python·tensorflow
学步_技术11 分钟前
Python编码系列—Python抽象工厂模式:构建复杂对象家族的蓝图
开发语言·python·抽象工厂模式
小黑爱编程29 分钟前
【LInux】HTTPS是如何实现安全传输的
linux·安全·https
BeyondESH34 分钟前
Linux线程同步—竞态条件和互斥锁(C语言)
linux·服务器·c++
Narutolxy1 小时前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
鱼饼6号1 小时前
Prometheus 上手指南
linux·运维·centos·prometheus
Asher Gu1 小时前
Linux系统编程入门 | 模拟实现 ls -l 命令
linux
Amo Xiang1 小时前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
c无序1 小时前
【Linux进程控制】进程程序替换
linux