Python shutil模块用法实例分析


Posted in Python onOctober 02, 2019

本文实例讲述了Python shutil模块用法。分享给大家供大家参考,具体如下:

shutil模块

主要作用与拷贝文件用的。

1.shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2。

import shutil
f1 = open("1.txt",encoding="utf-8")
f2 = open("2.txt","w",encoding="utf-8")
shutil.copyfileobj(f1,f2)

2.shutil.copyfile(文件1,文件2):不用打开文件,直接用文件名进行覆盖copy。

import shutil
shutil.copyfile("1.txt","3.txt")

3.shutil.copymode(文件1,文件2):之拷贝权限,内容组,用户,均不变。

def copymode(src,dst):
  """copy mode bits from src to dst"""
  if hasattr(os,'chmod'):
    st = os.stat(stc)
    mode = stat.S_IMODE(st.st_mode)
    os.chmod(dst,mode)

4.shutil.copystat(文件1,文件):只拷贝了权限。

def copystat(src,dst):
  """将所有的状态信息(模式位、时间、时间、标志)从src复制到dst"""
  st = os.stat(src)
  mode = stat.S_IMODE(st.st_mode)
  if hasattr(os, 'utime'):
    os.utime(dst,(st.st_atime,st.st_mtime))
  if hasattr(os, 'chmod')
    os.chmod(dst,mode)
  if hasattr(os, 'chflags') and hasattr(st,'st_flags'):
    try:
      os.chflags(dst, st.st_flags)
    except OSError,why:
      for err in 'EOPNOTSUPP', 'ENOTSUP':
        if hasattr(errno,err) and why.errno == getattr(errno, err):
          break
        else:
          raise

5.shutil.copy(文件1,文件2):拷贝文件和权限都进行copy。

def copy(src,dst):
  """copy data and mode bits ("cp src dst")
  The destination may be a directory.
  """
  if os.path.isdir(dst):
    dst = os.path.join(dst,os.path.basename(src))
    copyfile(src,dst)
    copymode(src,dst)

6.shutil.copy2(文件1,文件2):拷贝了文件和状态信息。

7.shutil.copytree(源目录,目标目录):可以递归copy多个目录到指定目录下。

  • shutil.ignore_patterns(*patterns)
  • shutil.copytree(src, dst, symlinks=False, ignore=None)

递归的去拷贝文件

例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

8.shutil.rmtree(目标目录):可以递归删除目录下的目录及文件。

9.shutil.move(源文件,指定路径):递归移动一个文件。

10.shutil.make_archive():可以压缩,打包文件。

import shutil
shutil.make_archive("shutil_archive_test","zip","D:\新建文件夹 (2)")

11.shutil.make_archive(base_name, format,...)

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

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    如:www =>保存至当前路径
    如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
  • format: 压缩包种类,"zip", "tar", "bztar","gztar"
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

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()
z.close()

tarfile 压缩解压

import tarfile
# 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()
# 解压
tar = tarfile.open('your.tar','r')
tar.extractall() # 可设置解压地址
tar.close()

第二种方法:

import zipfile
z = zipfile.ZipFile("day5.zip","w")
z.write("a")

解压:

z.extractall("a")

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python多线程编程(七):使用Condition实现复杂同步
Apr 05 Python
Python中用于转换字母为小写的lower()方法使用简介
May 19 Python
Python实现把json格式转换成文本或sql文件
Jul 10 Python
Python遍历文件夹和读写文件的实现方法
May 10 Python
详解Python pygame安装过程笔记
Jun 05 Python
Python 自动刷博客浏览量实例代码
Jun 14 Python
python sys,os,time模块的使用(包括时间格式的各种转换)
Apr 27 Python
python3.6.3转化为win-exe文件发布的方法
Oct 31 Python
python实现静态web服务器
Sep 03 Python
深入了解Python在HDA中的应用
Sep 05 Python
解决TensorFlow调用Keras库函数存在的问题
Jul 06 Python
Python爬虫使用bs4方法实现数据解析
Aug 25 Python
Windows平台Python编程必会模块之pywin32介绍
Oct 01 #Python
Python全栈之列表数据类型详解
Oct 01 #Python
python2和python3应该学哪个(python3.6与python3.7的选择)
Oct 01 #Python
使用Python制作一个打字训练小工具
Oct 01 #Python
Python + Flask 实现简单的验证码系统
Oct 01 #Python
python 矢量数据转栅格数据代码实例
Sep 30 #Python
python多进程间通信代码实例
Sep 30 #Python
You might like
利用PHP实现智能文件类型检测的实现代码
2011/08/02 PHP
解析smarty 截取字符串函数 truncate的用法介绍
2013/06/20 PHP
EarthLiveSharp中cloudinary的CDN图片缓存自动清理python脚本
2017/04/04 PHP
PHP简单实现遍历目录下特定文件的方法小结
2017/05/22 PHP
简明json介绍
2008/09/28 Javascript
javascript实现图片切换的幻灯片效果源代码
2012/12/12 Javascript
jquery使用ajax实现微信自动回复插件
2014/04/28 Javascript
使表格的标题列可左右拉伸jquery插件封装
2014/11/24 Javascript
Jquery网页内滑动缓冲导航的实现代码
2015/04/05 Javascript
精通JavaScript的this关键字
2020/05/28 Javascript
简单几步实现返回顶部效果
2016/12/05 Javascript
Bootstrap.css与layDate日期选择样式起冲突的解决办法
2017/04/07 Javascript
使用jQuery和ajax代替iframe的方法(详解)
2017/04/12 jQuery
vue实现长图垂直居上 vue实现短图垂直居中
2017/10/18 Javascript
AngularJs返回前一页面时刷新一次前面页面的方法
2018/10/09 Javascript
element ui table(表格)实现点击一行展开功能
2018/12/04 Javascript
Vue项目环境搭建详细总结
2019/09/26 Javascript
Vue结合路由配置递归实现菜单栏功能
2020/06/16 Javascript
JS highcharts动态柱状图原理及实现
2020/10/16 Javascript
浅析vue中的nextTick
2020/12/28 Vue.js
Django中使用locals()函数的技巧
2015/07/16 Python
详解tensorflow载入数据的三种方式
2018/04/24 Python
Python实现正弦信号的时域波形和频谱图示例【基于matplotlib】
2018/05/04 Python
pyqt5实现登录界面的模板
2020/05/30 Python
利用Python查看微信共同好友功能的实现代码
2019/04/24 Python
在Django admin中编辑ManyToManyField的实现方法
2019/08/09 Python
python 计算两个列表的相关系数的实现
2019/08/29 Python
python GUI库图形界面开发之PyQt5单行文本框控件QLineEdit详细使用方法与实例
2020/02/27 Python
浅谈在JupyterNotebook下导入自己的模块的问题
2020/04/16 Python
Python pickle模块常用方法代码实例
2020/10/10 Python
面试求职的个人自我评价
2013/11/16 职场文书
写给女朋友的检讨书
2014/01/28 职场文书
工程采购员岗位职责
2014/03/09 职场文书
社区居务公开实施方案
2014/03/27 职场文书
关爱留守儿童倡议书
2014/04/15 职场文书
python办公自动化之excel的操作
2021/05/23 Python