我有一组文件夹(名为 *.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()
您只打开一个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)
你也可以通过
@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)