代碼進行解壓和壓縮
代碼如下:
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import os import tarfile class software(object): def __init__(self): super(software, self).__init__() def start(self): # self.file_compression() # # self.file_uncompression() self.file() #解壓 def file_uncompression(self): tar = tarfile.open("123.tar.gz") tar.extractall("/opt/") # 解壓到的路徑 tar.close() # 將路徑中的文件 壓縮 def file_compression(self): cwd = os.getcwd() # 獲取當前路徑 print "cwd:",cwd tar = tarfile.open('test.tar', 'w:gz') # 把當前所有的文件 都壓縮 for root, dir, files in os.walk(cwd): for file in files: print "file:", file fullpath = os.path.join(root, file) print "fullpath:", fullpath tar.add(fullpath) #有選擇的解壓縮 # def file(self): # tar = tarfile.open("123.tar.gz") # tar.extractall(members=self.py_files(tar)) # tar.close() # def py_files(members): # for tarinfo in members: # if os.path.splitext(tarinfo.name)[1] == ".py": # yield tarinfo if __name__ == '__main__': print("main") s = software() s.start()
函數介紹:
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) 'r' or 'r:*' Open for reading with transparent compression (recommended). 'r:' Open for reading exclusively without compression. 'r:gz' Open for reading with gzip compression. 'r:bz2' Open for reading with bzip2 compression. 'a' or 'a:' Open for appending with no compression. The file is created if it does not exist. 'w' or 'w:' Open for uncompressed writing. 'w:gz' Open for gzip compressed writing. 'w:bz2' Open for bzip2 compressed writing.