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实现文件路径和url相互转换的方法
Jul 06 Python
Python数据结构之栈、队列的实现代码分享
Dec 04 Python
Python实现判断字符串中包含某个字符的判断函数示例
Jan 08 Python
python3 图片referer防盗链的实现方法
Mar 12 Python
python中找出numpy array数组的最值及其索引方法
Apr 17 Python
python利用pandas将excel文件转换为txt文件的方法
Oct 23 Python
numpy创建单位矩阵和对角矩阵的实例
Nov 29 Python
python实现将视频按帧读取到自定义目录
Dec 10 Python
python游戏开发的五个案例分享
Mar 09 Python
Python logging日志模块 配置文件方式
Jul 12 Python
python在地图上画比例的实例详解
Nov 13 Python
Python中文纠错的简单实现
Jul 07 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 setcookie设置Cookie用法(及设置无效的问题)
2011/07/13 PHP
php输出1000以内质数(素数)示例
2014/02/16 PHP
php输出金字塔的2种实现方法
2014/12/16 PHP
网页的分页下标生成代码(PHP后端方法)
2016/02/03 PHP
PHP实现限制IP访问的方法
2017/04/20 PHP
Laravel中前端js上传图片到七牛云的示例代码
2017/09/04 PHP
PHP hebrev()函数用法讲解
2019/02/21 PHP
JQuery 确定css方框模型(盒模型Box Model)
2010/01/22 Javascript
JQquery的一些使用心得分享
2012/08/01 Javascript
js或者jquery判断图片是否加载完成实现代码
2013/03/20 Javascript
JavaScript的类型、值和变量小结
2015/07/09 Javascript
js调用百度地图及调用百度地图的搜索功能
2015/09/07 Javascript
jquery实现倒计时功能
2015/12/28 Javascript
nodejs集成sqlite使用示例
2017/06/05 NodeJs
微信小程序wx:for和wx:for-item的用法详解
2018/04/01 Javascript
jQuery实现基本动画效果的方法详解
2018/09/06 jQuery
Vue 图片压缩并上传至服务器功能
2020/01/15 Javascript
jQuery 实现扁平式小清新导航
2020/07/07 jQuery
vue实现登录、注册、退出、跳转等功能
2020/12/23 Vue.js
Python使用迭代器打印螺旋矩阵的思路及代码示例
2016/07/02 Python
pyqt5实现登录界面的模板
2020/05/30 Python
pandas 数据结构之Series的使用方法
2019/06/21 Python
python多环境切换及pyenv使用过程详解
2019/09/27 Python
jupyter notebook 恢复误删单元格或者历史代码的实现
2020/04/17 Python
如何使用Django Admin管理后台导入CSV
2020/11/06 Python
Python做图像处理及视频音频文件分离和合成功能
2020/11/24 Python
python实现录制全屏和选择区域录屏功能
2021/02/05 Python
婴儿地球:Baby Earth
2018/12/25 全球购物
标记环介质访问控制协议
2016/03/27 面试题
入党转预备思想汇报
2014/01/07 职场文书
三年级科学教学反思
2014/01/29 职场文书
红头文件任命书范本
2014/06/05 职场文书
安全宣传标语
2014/06/10 职场文书
党干部专题民主生活会对照检查材料思想汇报
2014/10/06 职场文书
毕业纪念册寄语大全
2015/02/26 职场文书
出生证明格式
2015/06/15 职场文书