编写一个Python程序,每次下载压缩包形式的文件后,自动将内部文件解压到当前文件夹后将压缩包删除。
提到压缩文件就要分不同压缩格式进行讨论,主要有以下4种:
.gz:即gzip,通常只能压缩一个文件。
.tar:本质上不是压缩工具而是打包工具,可以跟.gz配合形成.tar.gz的打包压缩格式。
.zip:和.tar.gz很类似但可以打包压缩多个文件。
.rar:打包压缩文件,最初用于DOS。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import glob import os import gzip import tarfile import zipfile import rarfile import time
class unzip_files: def ungz(self, filename): filename = filename[:-3] gz_file = gzip.GzipFile(filename) with open(filename, "w+") as file: file.write(gz_file.read()) return filename def untar(self, filename): tar = tarfile.open(filename) names = tar.getnames() if not os.path.isdir(filename + "_dir"): os.mkdir(filename + "_dir") for name in names: tar.extract(name, filename + "_dir/") tar.close()
def unzip(self, filename): zip_file = zipfile.ZipFile(filename) if not os.path.isdir(filename + "_dir"): os.mkdir(filename + "_dir") for names in zip_file.namelist(): zip_file.extract(names, filename + "_dir/") zip_file.close()
def unrar(self, filename): rar = rarfile.RarFile(filename) if not os.path.isdir(filename + "_dir"): os.mkdir(filename + "_dir") os.chdir(filename + "_dir") rar.extractall() rar.close()
def main(self): for filename in filename_lst: if '.' in filename: suffix = filename.split('.')[-1] if suffix == 'gz': new_filename = self.ungz(path+'/'+filename) os.remove(path+'/'+filename) if new_filename.split('.')[-1] == 'tar': self.untar(path+'/'+new_filename) os.remove(path+'/'+new_filename) if suffix == 'tar': self.untar(path+'/'+filename) os.remove(path+'/'+filename) if suffix == 'zip': print(filename) self.unzip(path+'/'+filename) os.remove(path+'/'+filename) if suffix == 'rar': self.unrar(path+'/'+filename) os.remove(path+'/'+filename)
path = r'D:\\download'
while True: file_lst = glob.glob(path + '/*') filename_lst = [os.path.basename(i) for i in file_lst]
uzf = unzip_files() uzf.main() time.sleep(5)
|