必要なすべてのファイルを特定のフォルダーに入れたら、Pythonスクリプトでフォルダーの内容をzip形式で圧縮します。
これは可能ですか?
そして、どうすればそれを行うことができますか?
必要なすべてのファイルを特定のフォルダーに入れたら、Pythonスクリプトでフォルダーの内容をzip形式で圧縮します。
これは可能ですか?
そして、どうすればそれを行うことができますか?
Python 2.7 では、以下を使用できます: shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])。
base_nameアーカイブ名から拡張子を引いたもの
formatアーカイブの形式
圧縮するroot_dirディレクトリ。
例えば
shutil.make_archive(target_file, format="bztar", root_dir=compress_me)
スクリプトの適応バージョンは次のとおりです。
#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os
def zipdir(basedir, archivename):
assert os.path.isdir(basedir)
with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(basedir):
#NOTE: ignore empty directories
for fn in files:
absfn = os.path.join(root, fn)
zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
z.write(absfn, zfn)
if __name__ == '__main__':
import sys
basedir = sys.argv[1]
archivename = sys.argv[2]
zipdir(basedir, archivename)
例:
C:\zipdir> python -mzipdir c:\tmp\test test.zip
ディレクトリ'C:\zipdir\test.zip'
の内容でアーカイブを作成します。'c:\tmp\test'
ここに再帰バージョンがあります
def zipfolder(path, relname, archive):
paths = os.listdir(path)
for p in paths:
p1 = os.path.join(path, p)
p2 = os.path.join(relname, p)
if os.path.isdir(p1):
zipfolder(p1, p2, archive)
else:
archive.write(p1, p2)
def create_zip(path, relname, archname):
archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
if os.path.isdir(path):
zipfolder(path, relname, archive)
else:
archive.write(path, relname)
archive.close()
ただし、jfsのソリューションとKozyarchukのソリューションの両方がOPのユースケースで機能する可能性があります。
したがって、ソース フォルダー (および任意の深さのサブフォルダー) を単純に zip アーカイブに追加するソリューションを次に示します。これは、フォルダー名を組み込みメソッドに渡すことができないという事実が原因です。ZipFile.write()
以下の関数 はadd_folder_to_zip()
、フォルダーとそのすべてのコンテンツを zip アーカイブに追加する簡単な方法を提供します。以下のコードは Python2 と Python3 で動作します。
import zipfile
import os
def add_folder_to_zip(src_folder_name, dst_zip_archive):
""" Adds a folder and its contents to a zip archive
Args:
src_folder_name (str): Source folder name to add to the archive
dst_zip_archive (ZipFile): Destination zip archive
Returns:
None
"""
for walk_item in os.walk(src_folder_name):
for file_item in walk_item[2]:
# walk_item[2] is a list of files in the folder entry
# walk_item[0] is the folder entry full path
fn_to_add = os.path.join(walk_item[0], file_item)
dst_zip_archive.write(fn_to_add)
if __name__ == '__main__':
zf = zipfile.ZipFile('myzip.zip', mode='w')
add_folder_to_zip('zip_this_folder', zf)
zf.close()