1. 程式人生 > 程式設計 >python 解壓、複製、刪除 檔案的例項程式碼

python 解壓、複製、刪除 檔案的例項程式碼

壓縮複製刪除檔案基於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)
 # 註釋原始碼
 # 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 解壓、複製、刪除 檔案內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!