[英]Why compression output larger zip file
I really don't understand about python compression because whenever I am trying to compress a folder or file I end up getting a very larger file 5.5 times bigger than the original file.我真的不了解 python 压缩,因为每当我尝试压缩文件夹或文件时,我最终都会得到一个比原始文件大 5.5 倍的非常大的文件。 Why does this happen?
为什么会发生这种情况? Is there any way I can compress a folder or a file with python and get an output that's at most the size of the original file?
有什么方法可以用python压缩文件夹或文件并获得最多与原始文件大小相同的输出? Here is the code I am using.
这是我正在使用的代码。
import os, zipfile
def zipfiles(filename, destname):
try:
zf = zipfile.ZipFile(destname, 'w', zipfile.ZIP_DEFLATED)
for dirname, subdirs, files in os.walk(filename):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
except Exception, e:
print str(e)
def main():
x = raw_input('Enter Filename: ')
while len(x) == 0:
x = raw_input('Enter Filename: ')
y = raw_input('Enter destination name: ')
while len(y) == 0:
y = raw_input('Enter destination name: ')
zipfiles(x, y+'.zip')
main()
Make sure that the destination .zip
file is not in the same folder you are compressing, otherwise your script may be adding a copy of itself to itself — which obviously will make it much bigger.确保目标
.zip
文件不在您正在压缩的同一个文件夹中,否则您的脚本可能会向自身添加其自身的副本——这显然会使它变得更大。
Here's a revised version of your code that will skip the archive when it's being created in the same directory folder:这是您的代码的修订版本,当它在同一目录文件夹中创建时将跳过存档:
import os, zipfile
def zipfiles(source_folder, destination_name):
source_folder = os.path.abspath(source_folder)
destination_path = os.path.abspath(destination_name)
try:
with zipfile.ZipFile(destination_name, 'w', zipfile.ZIP_DEFLATED) as zf:
for dirname, subdirs, files in os.walk(source_folder):
# zf.write(dirname) # Not needed.
for filename in files:
filepath = os.path.join(dirname, filename)
if filepath != destination_path: # Skip destination file.
zf.write(filepath)
except Exception as e:
print(e)
def main():
x = ''
while not x:
x = raw_input('Enter source folder name: ')
y = ''
while not y:
y = raw_input('Enter destination archive file name: ')
zipfiles(x, y+'.zip')
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.