python文件操作2
import os
import zipfile
import sys
cwd = os.getcwd()
start = cwd.rfind(os.sep)+1
zfile = cwd[start:]+".zip"
z = zipfile.ZipFile(zfile,mode="w",compression=zipfile.ZIP_DEFLATED)
try:
for dirpath,dirs,files in os.walk(cwd):
for file in files:
if file == zfile or file == "zip.py":
continue
z_path = os.path.join(dirpath,file)
z.write(z_path,z_path[start:])
z.close()
finally:
if z:
z.close()
import os
import zipfile
import sys
cwd = os.getcwd()
start = cwd.rfind(os.sep)+1
zfile = cwd[start:]+".zip"
z = zipfile.ZipFile(zfile,mode="w",compression=zipfile.ZIP_DEFLATED)
try:
for dirpath,dirs,files in os.walk(cwd):
for file in files:
if file == zfile or file == "zip.py":
continue
z_path = os.path.join(dirpath,file)
z.write(z_path,z_path[start:])
z.close()
finally:
if z:
z.close()
格式编码的压缩和解压缩的module,zipfile里有两个非常重要的class:ZipFile和ZipInfo。ZipFile是主要的类,用来创建和读取zip文件而ZipInfo是存储的zip文件的每个文件的信息。
在这里我需要把一个目录压缩,这就要将目录里的文件一个文件一个文件的加入,然后在使用zipfile的ZipFile类的时候,再一个一个写入压缩文件。
代码
1#!/usr/bin/env python
2#coding=utf-8
3
4import os
5import zipfile
6
7filelist = []
8for root, dirs, files in os.walk("D:\\clean"):
9 for name in files:
10 filelist.append(os.path.join(root, name))
11
12zf = zipfile.ZipFile("d:\\test.zip", "w", zipfile.zlib.DEFLATED)
13for tar in filelist:
14 zf.write(tar)
python中使用ZIP压缩备份
import os
import zipfile
import time
# 压缩目录
source_dir = r'F:\web'
# 按时间生成文件名称
target_file = time.strftime('%Y%m%d%H%M%S') + '.zip'
myZipFile = zipfile.ZipFile(target_file, 'w' )
# 压缩所有文件,包含子目录
for root,dirs,files in os.walk(source_dir):
&nbs>Python压缩文件 2011-08-07 14:50 浏览 99 评论(0) 分类:编程语言