我不确定我做错了什么,但我需要的是创建一个包含给定目录的所有文件和文件夹(空或不)的zip文件。所以,目前我有这个简单的代码“工作”,但它不会添加空文件夹:|
c:\ temp \ trashtests
的内容c:\temp\trashtests\a\a.txt
c:\temp\trashtests\b\b.txt
c:\temp\trashtests\c
c:\temp\trashtests\d
当前代码:
class ZipTools:
"""
Zip tools
"""
def __init__(self, target_path=None, zip_name=None):
self.path = target_path
self.zip_name = zip_name
def create_zip(self):
shutil.make_archive(self.zip_name, format='zip', root_dir=self.path)
执行:
ab = self.ZipTools('c:\ temp \ trashtests','c:\ test \ a.zip') ab.create_zip()
输出是一个zip文件,只有:
\a\a.txt
\b\b.txt
那么,如何使用shutils创建包含给定目录的所有内容的zip文件?如果没有,我怎么能用zipfile来做呢?
提前致谢。
编辑:
正如J.F. Sebastian所说,我尝试了this question的解决方案,但由于它创建了一个具有以下结构的zip文件,因此无效:
文件: a.zip 含量:
c:
a\a.txt
b\b.txt
我仍在试图找出解决方案:)
答案 0 :(得分:0)
我能够使用此代码解决此问题:
重要提示,此代码适用于我需要的内容,即:
压缩与要创建的zip文件名相同的现有文件夹。
import os
import sys
import zipfile
class ZipTools:
"""
Zip tools
"""
def __init__(self, folder_path=None, pkg_zip=None):
self.path = folder_path
self.zip_name = pkg_zip
self.temp_dir = 'c:\\temp'
self.archive = '{p}\\{z}'.format(p=self.temp_dir, z='a.zip')
def zip(self):
parent_folder = os.path.dirname(self.path)
# Retrieve the paths of the folder contents.
contents = os.walk(self.path)
try:
zip_file = zipfile.ZipFile(self.archive, 'w', zipfile.ZIP_DEFLATED)
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
ab_path = os.path.join(root, folder_name)
rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
print rel_path
zip_file.write(ab_path, rel_path)
for file_name in files:
ab_path = os.path.join(root, file_name)
rel_path = ab_path.replace(parent_folder + '\\' + self.zip_name, '')
zip_file.write(ab_path, rel_path)
except zipfile.BadZipfile, message:
print message
sys.exit(1)
finally:
zip_file.close()
if __name__ == '__main__':
ab = ZipTools('c:\\temp\\trashtests', 'a.zip')
ab.zip()