我真的不了解python压缩,因为每当我尝试压缩文件夹或文件时,我最终得到的文件比原始文件大5.5倍。为什么会这样?有什么办法可以用python压缩文件夹或文件,并获得最多与原始文件大小相同的输出?这是我正在使用的代码。
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()
答案 0 :(得分:2)
确保目标.zip
文件不在您正在压缩的文件夹中,否则您的脚本可能会将自身的副本添加到自身 - 这显然会使其更大。
以下是您的代码的修订版本,该代码将在同一目录文件夹中创建时跳过存档:
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:
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()