python 解压、复制、删除 文件的实例代码


Posted in Python onFebruary 26, 2020

压缩复制删除文件基于python语言怎么操作呢,压缩文件有四种格式:zip、rar、tar、tar.gz,在压缩过程中也容易出现很多问题,今天小编通过代码给大家详解,具体内容如下所示:

一、python3解压文件

1.python 解压文件代码示例

如下代码主要实现zip、rar、tar、tar.gz四种格式的压缩文件的解压

def unzip_file(src_file, dst_dir=None, unzipped_files=None, del_flag=True):
 """
 根据指定的压缩文件类型递归解压所有指定类型的压缩文件
 :param src_file: 解压的源文件路径,可以为文件夹路径也可以是文件路径
 :param dst_dir: 解压后的文件存储路径
 :param unzipped_files: 完成解压的文件名列表
 :param del_flag: 解压完成后是否删除原压缩文件,默认删除
 :return: 完成解压的文件名列表
 """
 # 完成解压的文件名列表初始为空
 if unzipped_files is None:
  unzipped_files = []
 # 指定的解压文件类型
 zip_types = ['.zip', '.rar', '.tar', '.gz']

 def exec_decompress(zip_file, dst_dir):
  """
  解压实现的公共代码
  :param zip_file: 压缩文件全路径
  :param dst_dir: 解压后文件存储路径
  :return:
  """
  file_suffix = os.path.splitext(zip_file)[1].lower()
  try:
   print('Start extracting the file: %s' % zip_file)

   # zip 解压
   if file_suffix == '.zip':
    # zip解压 写法一
    with ZipFile(zip_file, mode='r') as zf:
     zf.extractall(dst_dir)
    # zip解压 写法二
    # file_zip = ZipFile(zip_file, mode='r')
    # for file in file_zip.namelist():
    #  file_zip.extract(file, dst_dir)
    # file_zip.close()

   # rar 解压
   elif file_suffix == '.rar':
    rf = rarfile.RarFile(zip_file)
    rf.extractall(dst_dir)

   # tar、tgz(tar.gz) 解压
   elif file_suffix in ['.tar', '.gz']:
    tf = tarfile.open(zip_file)
    tf.extractall(dst_dir)
    # 关闭文件释放内存
    tf.close()

   print('Finished extracting the file: %s' % zip_file)
  except Exception as e:
   print(e)
  # 解压完成加入完成列表
  unzipped_files.append(zip_file)
  # 根据标识执行原压缩文件删除
  if del_flag and os.path.exists(zip_file):
   os.remove(zip_file)

 # 如果传入的文件路径为文件目录,则遍历目录下所有文件
 if os.path.isdir(src_file):
  # 初始化文件目录下存在的压缩文件集合为空
  zip_files = []
  # 如果传入的目的文件路径为空,则取解压的原文件夹路径
  dst_dir = dst_dir if dst_dir else src_file
  # 遍历目录下所有文件
  for file in os.listdir(src_file):
   file_path = os.path.join(src_file, file)
   # 如果是文件夹则继续递归解压
   if os.path.isdir(file_path):
    dst_path = os.path.join(dst_dir, file)
    unzip_file(file_path, dst_path, unzipped_files)
   # 如果是指定类型的压缩文件则加入到压缩文件列表
   elif os.path.isfile(file_path) and os.path.splitext(file_path)[
    1].lower() in zip_types and file_path not in unzipped_files:
    zip_files.append(file_path)
  # 遍历压缩文件列表,执行压缩文件的解压
  for zip_file in zip_files:
   exec_decompress(zip_file, dst_dir)
  # 如果当前目录存在压缩文件则完成所有文件解压后继续遍历
  if zip_files:
   unzip_file(dst_dir, unzipped_files=unzipped_files)
 # 如果传入的文件路径是指定类型的压缩文件则直接执行解压
 elif os.path.isfile(src_file) and os.path.splitext(src_file)[1].lower() in zip_types:
  dst_dir = dst_dir if dst_dir else os.path.dirname(src_file)
  exec_decompress(src_file, dst_dir)

 return unzipped_files

2.python解压常见问题解决办法

2.1 python3 zipfile解压文件名乱码解决办法

直接修改源码,即 zipfile.py 文件:

第一处:

if flags & 0x800:
 # UTF-8 file names extension
 filename = filename.decode('utf-8')
else:
 # Historical ZIP filename encoding
 # 注释原代码
 # filename = filename.decode('cp437')
 # 新加一行代码
 filename = filename.decode('gbk')

 第二处:

if zinfo.flag_bits & 0x800:
 # UTF-8 filename
 fname_str = fname.decode("utf-8")
else:
 # 注释原代码
 # fname_str = fname.decode("cp437")
 # 同样新加一行代码
 fname_str = fname.decode('gbk')

2.1 rar 解压无法找到动态库(unrar.dll)解决办法

报错示例:

python 解压、复制、删除 文件的实例代码

第一步 手动下载动态库文件 unrar.dll 存在本地目录,例如我的本地存储路径为:C:\MySoft\assist\unrar.dll

链接: https://pan.baidu.com/s/1rqhFND9XmtD1Y8yGLEz9kA 提取码: u2my

第二步 修改源码 unrarlib.py 文件

if platform.system() == 'Windows':
 from ctypes.wintypes import HANDLE as WIN_HANDLE
 HANDLE = WIN_HANDLE
 UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint,
          ctypes.c_long, ctypes.c_long,
          ctypes.c_long)
 # 注释原代码
 # lib_path = lib_path or find_library("unrar.dll")
 # 将路径指向下载的动态库文件存储路径
 lib_path = r"C:\MySoft\assist\unrar.dll"
 if lib_path:
  unrarlib = ctypes.WinDLL(lib_path)

知识点扩展:python 压缩文件夹的代码

def zip_ya(start_dir):
  start_dir = start_dir # 要压缩的文件夹路径
  file_news = start_dir + '.zip' # 压缩后文件夹的名字

  z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
  for dir_path, dir_names, file_names in os.walk(start_dir):
   f_path = dir_path.replace(start_dir, '') # 这一句很重要,不replace的话,就从根目录开始复制
   f_path = f_path and f_path + os.sep or '' # 实现当前文件夹以及包含的所有文件的压缩
   for filename in file_names:
    z.write(os.path.join(dir_path, filename), f_path + filename)
  z.close()
  return file_news

PS: 若递归扫描所有文件夹过程中有文件夹里不存在文件, 该文件夹将被忽略

总结

到此这篇关于python 解压、复制、删除 文件的实例代码的文章就介绍到这了,更多相关python 解压、复制、删除 文件内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python接收Gmail新邮件并发送到gtalk的方法
Mar 10 Python
30分钟搭建Python的Flask框架并在上面编写第一个应用
Mar 30 Python
Python3字符串学习教程
Aug 20 Python
python 计算文件的md5值实例
Jan 13 Python
Python随机生成均匀分布在单位圆内的点代码示例
Nov 13 Python
使用Python+Splinter自动刷新抢12306火车票
Jan 03 Python
python打包生成的exe文件运行时提示缺少模块的解决方法
Oct 31 Python
Python 面试中 8 个必考问题
Nov 16 Python
python实现FTP循环上传文件
Mar 20 Python
windows python3安装Jupyter Notebooks教程
Apr 13 Python
python中绕过反爬虫的方法总结
Nov 25 Python
在 Golang 中实现 Cache::remember 方法详解
Mar 30 Python
Python递归调用实现数字累加的代码
Feb 25 #Python
python烟花效果的代码实例
Feb 25 #Python
python GUI库图形界面开发之PyQt5控件QTableWidget详细使用方法与属性
Feb 25 #Python
使用python绘制cdf的多种实现方法
Feb 25 #Python
python GUI库图形界面开发之PyQt5开发环境配置与基础使用
Feb 25 #Python
python GUI库图形界面开发之PyQt5信号与槽基本操作
Feb 25 #Python
python GUI库图形界面开发之PyQt5信号与槽机制、自定义信号基础介绍
Feb 25 #Python
You might like
php+xml编程之xpath的应用实例
2015/01/24 PHP
详解ThinkPHP3.2.3验证码显示、刷新、校验
2016/12/29 PHP
laravel 使用auth编写登录的方法
2019/09/30 PHP
W3C Group的JavaScript1.8 新特性介绍
2009/05/19 Javascript
关于JavaScript与HTML的交互事件
2013/04/12 Javascript
JS代码判断IE6,IE7,IE8,IE9的函数代码
2013/08/02 Javascript
ashx文件获取$.ajax()方法发送的数据
2016/05/26 Javascript
JavaScript编写九九乘法表(两种任选)
2017/02/04 Javascript
详解Node.js利用node-git-server快速搭建git服务器
2017/09/27 Javascript
简单实现vue中的依赖收集与响应的方法
2019/02/18 Javascript
微信小程序按钮点击跳转页面详解
2019/05/06 Javascript
深入学习Vue nextTick的用法及原理
2019/10/08 Javascript
javascript网页随机点名实现过程解析
2019/10/15 Javascript
node.js使用net模块创建服务器和客户端示例【基于TCP协议】
2020/02/14 Javascript
微信小程序实现手指拖动选项排序
2020/04/22 Javascript
用实例说明python的*args和**kwargs用法
2013/11/01 Python
python爬虫自动创建文件夹的功能
2018/08/01 Python
PyQT5 QTableView显示绑定数据的实例详解
2019/06/25 Python
详解python破解zip文件密码的方法
2020/01/13 Python
详解Python中namedtuple的使用
2020/04/27 Python
python使用自定义钉钉机器人的示例代码
2020/06/24 Python
Marriott国际:万豪国际酒店查询预订
2017/09/25 全球购物
美国购买舞会礼服网站:Couture Candy
2019/12/29 全球购物
精伦电子Java笔试题
2013/01/16 面试题
企业项目策划书
2014/01/11 职场文书
酒店管理求职信范文
2014/04/06 职场文书
环保建议书400字
2014/05/14 职场文书
个人校本研修方案
2014/05/26 职场文书
2014小学生国庆65周年演讲稿
2014/09/21 职场文书
大学生联谊活动策划书(光棍节)
2014/10/10 职场文书
寻找成龙观后感
2015/06/12 职场文书
老舍《猫》教学反思
2016/02/17 职场文书
Python办公自动化之Excel(中)
2021/05/24 Python
JVM入门之类加载与字节码技术(类加载与类的加载器)
2021/06/15 Java/Android
SQL Server数据库基本概念、组成、常用对象与约束
2022/03/20 SQL Server
Python os和os.path模块详情
2022/04/02 Python