9-20
# example of compressing a gzip file
import gzip
inF = file("x.txt", 'rb')
s = inF.read()
inF.close()
outF = gzip.GzipFile("x.txt.gz", 'wb')
outF.write(s)
outF.close()
# example of decompressing a gzip file
inf = gzip.GzipFile('x.txt.gz')
s = inf.read()
inf.close()
outf = open('x.txt', 'wb')
outf.write(s)
outf.close()
# example of compressing a bzip2 file
import bz2
inf = open('e:\\yan.txt')
s = inf.read()
inf.close()
outf = bz2.BZ2File('e:\\yan.txt.bzip2', 'wb')
outf.write(s)
outf.close()
print 'done'
# example of decompressing a bzip2 file
inf = bz2.BZ2Compressor('x.txt.bzip2')
s = inf.read()
inf.close()
outf = open('x.txt', 'wb')
outf.write(s)
outf.close()
9-21
import zipfile
def dowithzip():
prompt = '''
A: add a file to archive
B: extract a file from archive
C: create a zip archive
Enter your choice: '''
while True:
try:
choice = raw_input(prompt).strip().lower()
except (EOFError, KeyboardInterrupt):
choice = 'q'
if choice not in 'abc':
print 'Wrong input, try again'
else:
break
filename = raw_input('your zipfile name: ')
if choice == 'a':
f = zipfile.ZipFile(filename, 'a')
f.write(raw_input('file you want to add: '))
elif choice == 'b':
f = zipfile.ZipFile(filename)
f.extract(raw_input('file you want to extract: '), raw_input('extract-to path: '))
else:
f = zipfile.ZipFile(filename, 'w')
f.close()
print 'done'
dowithzip()
9-22
import zipfile
def lszip():
zipfilename = raw_input('your zip-file name: ')
thezipfile = zipfile.ZipFile(zipfilename)
thenamelist = thezipfile.namelist()
theinfolist = thezipfile.infolist()
filenum = len(theinfolist)
for i in range(filenum):
print "{0}'s size is {1}".format(thenamelist[i], theinfolist[i].compress_size)
print "{0}'s compression ratio: {1:.3f}".format(thenamelist[i],
float(theinfolist[i].compress_size) / theinfolist[i].file_size)
print "timestamp: {0}".format(theinfolist[i].date_time)
lszip()
9-23
import tarfile
import os.path
def lszip():
tarfilename = raw_input('your tar-file name: ')
basename = os.path.splitext(tarfilename)[1]
thetarfile = tarfile.open(tarfilename, 'r:' + basename[1:])
thenamelist = thetarfile.getnames()
theinfolist = thetarfile.getmembers()
filenum = len(theinfolist)
for i in range(filenum):
print "{0}'s size is {1}".format(thenamelist[i], theinfolist[i].size)
print "timestamp: {0}".format(theinfolist[i].mtime)
lszip()
9-24
import zipfile
import tarfile
import os.path
def movefile():
filefrom = raw_input('the file is from(the compressed file name): ')
fileto = raw_input('move the file to(the compressed file name): ')
# open the file
if filefrom.endswith('.zip'):
ffrom = zipfile.ZipFile(filefrom, 'r')
fto = zipfile.ZipFile(fileto, 'w')
else:
# support .tar.gz and .tar.bz2 file
basename1 = os.path.splitext(filefrom)[1]
basename2 = os.path.splitext(fileto)[1]
ffrom = tarfile.open(filefrom, 'r:' + basename1[1:])
fto = tarfile.open(fileto, 'w:' + basename2[1:])
# extract the file
thefile = ffrom.extract(raw_input('file to extract: '))
# move the file
if fileto.endswith('.zip'):
fto.write(thefile)
else:
fto.add(thefile)
ffrom.close()
fto.close()
movefile()
9-25
import tarfile
import zipfile
import os
import os.path
adic = {'.zip': zipfile.ZipFile,
'.tar.gz': tarfile.open,
'.tar.bz2': tarfile.open,
'.tgz': tarfile.open,
'.tbz': tarfile.open}
bdic = {'.zip': 'r',
'.tar.gz': 'r:gz',
'.tar.bz2': 'r:bz2',
'.tgz': 'r:gz',
'.tbz': 'r:bz2',
'.tar.bzip2': 'r:bz2'}
# .gz or .bz2 file is not archive file
def decompressfile(directory, archive):
num = len(archive)
for i in range(num):
archivefile_name = archive[i]
archivefile_base = '.' + archivefile_name.split('.', 1)[1]
archivefile = adic[archivefile_base](archivefile_name, bdic[archivefile_base])
if i == 0:
archivefile.extractall(directory)
else:
os.chdir(directory)
os.mkdir(archivefile_name.split('.')[0])
archivefile.extractall(archivefile_name.split('.')[0])
archivefile.close()
print 'done'