我有一组文件夹(名为* .pages),我想将其压缩到各自的.zip文件中,例如“example1.pages”进入“example1.pages.zip”,“example2.pages”进入“example2.pages.zip”等。我还想要包含各个.pages文件夹的内容。
目前,该脚本将所有.pages文件压缩为具有嵌套目录的单个文件。
我不知道如何继续,我相信在执行zipfile功能时我会遗漏一些东西。
非常感谢任何帮助!
import os
import zipfile
start_path = "MY/DIRECTORY/HERE"
def zipdir(ziph):
dir_count = 0
file_count = 0
for (path,dirs,files) in os.walk(start_path):
print('Directory: {:s}'.format(path))
dir_count += 1
for file in dirs:
if file.endswith(".pages"):
print('\nAttempting to zip: \'{}\''.format(file))
ziph.write(os.path.join(path, file))
print('Done')
file_count += 1
print('\nProcessed {} files in {} directories.'.format(file_count,dir_count))
if __name__ == '__main__':
zipf = zipfile.ZipFile("NAME/OF/INDIVIDUAL/ZIP/FILE.zip", 'w', zipfile.ZIP_DEFLATED)
zipdir(zipf)
zipf.close()
答案 0 :(得分:0)
您只需打开一个zip文件并在其中添加所有内容。如果每个文件需要一个zip,则需要在扫描文件时在循环中创建zip文件。
import os
import zipfile
start_path = "MY/DIRECTORY/HERE"
start_path = '.'
def zipdir(start_path):
dir_count = 0
file_count = 0
for (path,dirs,files) in os.walk(start_path):
print('Directory: {:s}'.format(path))
dir_count += 1
for file in files:
if file.endswith(".pages"):
file_path = os.path.join(path, file)
print('\nAttempting to zip: \'{}\''.format(file_path))
with zipfile.ZipFile(file_path + '.zip', 'w', zipfile.ZIP_DEFLATED) as ziph:
ziph.write(file_path, file)
print('Done')
file_count += 1
print('\nProcessed {} files in {} directories.'.format(file_count,dir_count))
if __name__ == '__main__':
zipdir(start_path)
答案 1 :(得分:0)
您还可以采用@tdelaney的代码并按以下方式使用shutil模块:
enter import os
import shutil
reports_path = os.getcwd()
def zipdir(reports_path):
for (path,dirs,files) in os.walk(reports_path):
for d in dirs:
file_path = os.path.join(path, d)
print 'Compressing ' + d
shutil.make_archive(d,'zip',file_path)
print "Done"
if __name__ == '__main__':
zipdir(reports_path)