对文件进行解压缩是我们日常工作中最平常不过的行为了,压缩过的文件不仅可以节省磁盘空间,而且在网络传输中也可以节省不少时间。
Python为我们提供了zipfile模块,这使得我们可以十分方便地对文件进行解压缩操作,而且代码书写也十分简单:
对文件进行压缩:
from zipfile import ZipFileimport osdef get_all_file_paths(directory):file_paths = []# 把所有的文件夹以及子文件夹、以及文件全部搞出来for root, directories, files in os.walk(directory):for filename in files:# 得到完全路径filepath = os.path.join(root, filename)file_paths.append(filepath)return file_pathsdef main():directory = './Junit'file_paths = get_all_file_paths(directory)print('Following files will be zipped:')for file_name in file_paths:print(file_name)with ZipFile('my_python_files.zip', 'w') as zip:for file in file_paths:zip.write(file)print('All files zipped successfully!')if __name__ == "__main__":main()
输出:
Following files will be zipped:./Junit\hamcrest-core-1.3.jar./Junit\junit-4.11-javadoc.jar./Junit\junit-4.11-sources.jar./Junit\junit-4.11.jar./Junit\junit-4.7.jarAll files zipped successfully!
不过这个算法的压缩率貌似不是很高,至少在这个文件上跟360比还是差100KB。
对压缩文件进行解压:
from zipfile import ZipFilefile_name = "Junit 4.11.zip"with ZipFile(file_name, 'r') as zip:# printing all the contents of the zip filezip.printdir()print('Extracting all the files now...')zip.extractall()print('Done!')
输出:
File NameModified SizeJunit/ -04-22 20:51:10 0Junit/hamcrest-core-1.3.jar-04-22 19:04:48 45024Junit/junit-4.11-javadoc.jar -04-22 19:04:00 379344Junit/junit-4.11-sources.jar -04-22 19:03:42 151329Junit/junit-4.11.jar -04-22 19:03:32 245039Junit/junit-4.7.jar -04-22 19:04:00 232354Extracting all the files now...Done!
如果觉得《利用Python对文件进行解压缩》对你有帮助,请点赞、收藏,并留下你的观点哦!