Home > Backend Development > Python Tutorial > Python3实现将文件归档到zip文件及从zip文件中读取数据的方法

Python3实现将文件归档到zip文件及从zip文件中读取数据的方法

WBOY
Release: 2016-06-10 15:11:50
Original
1541 people have browsed it

本文实例讲述了Python3实现将文件归档到zip文件及从zip文件中读取数据的方法。分享给大家供大家参考。具体实现方法如下:

''''' 
Created on Dec 24, 2012 
将文件归档到zip文件,并从zip文件中读取数据 
@author: liury_lab 
''' 
# 压缩成zip文件 
from zipfile import *  #@UnusedWildImport 
import os 
 
my_dir = 'd:/中华十大名帖/' 
myzip = ZipFile('d:/中华十大名帖.zip', 'w', ZIP_DEFLATED) 
for file_name in os.listdir(my_dir): 
  file_path = my_dir + file_name 
  print(file_path) 
  myzip.write(file_path) 
myzip.close() 
 
print('finished') 
 
# 从zip 文件中读取数据 
# 直接检查一个zip格式的归档文件中部分或所有的文件,
# 同时还要避免将这些文件展开到磁盘上 
my_zip = ZipFile('d:/中华十大名帖.zip') 
for file_name in my_zip.namelist(): 
  print('File:', file_name, end = ' ') 
  file_bytes = my_zip.read(file_name) 
  print('has ', len(file_bytes), ' bytes') 

Copy after login

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template