package into zip file
Import ZipFile
f = zipfile. ZipFile (' Archive.zip ', ' W ', ZipFile. zip_deflated)
f.write (' file_to_add.py ')
f.close ()
unpack from zip file
Import os,sys
import zipfile
import re
os.chdir ('/home/wangyue/brain/geneexpression ') all
= Os.listdir ('. ')
For II in all:
B = re.match (' \d+ ', ii)
if B:
zfile = II
z = zipfile. ZipFile (Zfile, mode= ' R ')
os.mkdir (' un ' + II) for
JJ in z.filelist:
data = Z.read (JJ)
fd = open ('./' + ' UN ' +ii+ '/' +jj.filename, ' WB ')
fd.write (data)
Fd.close ()
package The files in the entire folder
Import ZipFile
f = zipfile. ZipFile (' Archive.zip ', ' W ', ZipFile. zip_deflated)
Startdir = "C:\\mydirectory"
for Dirpath, Dirnames, filenames in Os.walk (startdir):
for FileName in filenames:
f.write (Os.path.join (dirpath,filename))
F.close ()
The code fragment comes from: http://www.sharejs.com/codes/python/210
Compress and decompress tar.gz files
First decompression
Import tarfile
import OS
def untar (fname, dirs):
t = Tarfile.open (fname)
t.extractall (path = dirs)
if __name__ = = "__main__":
Untar ("del.tar.gz", ".")
Again is compression
Import tarfile
import OS
def tar (fname):
t = tarfile.open (fname + ". tar.gz", "W:gz") for
root, dir, files In Os.walk (fname):
print root, dir, files to
file in files:
FullPath = os.path.join (root, file)
T.add (f Ullpath)
t.close ()
if __name__ = = "__main__":
tar ("del")
The above references are from
Http://www.cnblogs.com/kaituorensheng/p/4493145.html