压缩文件:
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):
for vfileName in files:
fileName = os.path.join(root,vfileName)
myZipFile.write( fileName, fileName, zipfile.ZIP_DEFLATED )
# 压缩完成
myZipFile.close()
Gzip File Handling. The gzip
module provides function and class definitions that make it easy to handle simple Gzip files. These allow you to open a compressed file and read it as if it were already decompressed. They also allow you to open a file and write to it, having the data automatically compressed as you write.
gzip.open
(filename
,mode
,level
,fileobj
) →gzip.GzipFile
Open the file named
filename
with the givenmode
('r'
,'w'
or'a'
). The compressionlevel
is an integer that provides a preference for speed versus size. As an alternative, you can open a file or socket separately and provide afileobj
, for example,f= open('somefile','r'); zf= gzip.open( fileobj=f )
.
Once this file is open, it can perform ordinary read
, readline
, readlines
, write
, writeline
, and writelines
operations. If you open the file with 'rb'
mode, the various read functions will decompress the file's contents as the file is read. If you open the file with 'wb'
or 'ab'
modes, the various write functions will compress the data as they write to the file.
1 1 | how can I create a .tar.gz file which compress the data as much tar can...
| |||
| ||||
3 | You call tarfile.open with You'll probably want to end the filename (the BTW, you usually get better compression with a mode of | |||
|
0 | tarfile module is cool: http://docs.python.org/library/tarfile.html | ||
add comment |
1 |
If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2". |