7
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonでフォルダやファイルをZIP化する方法

Last updated at Posted at 2017-10-19

はじめに

Pythonを使って、ZIP化する方法を載せておきます。
ファイルのZIP化はzipfileライブラリーでできますが、フォルダごとZIP化というのが調べた限り無いようです。

ソースコード

zip.py
import os
import zipfile

def get_file_path(file_path):
    """
    ファイルパスから指定以下のファイルの一覧を取得する
    :param file_path:ファイルパス
    :return: generator
    """
    if os.path.isfile(file_path):
        yield file_path
    else:
        for (base_dir, _ , file_name_list) in os.walk(file_path):
            for file_name in file_name_list:
                path = os.path.join(base_dir, file_name)
                path = path.replace(os.sep, '/')
                yield path


def zipping(file_path, save_dir=""):
    """
    ファイル及びフォルダごとZIP化関数
    :param file_path: 圧縮対象のファイルおよびディレクトリ
    :param save_dir: 保存先(デフォルトは圧縮対象と同じ階層)
    :return:
    """
    if file_path[-1]==os.sep or file_path[-1]=="/" :
        file_path = file_path[:-1]

    if not os.path.isdir(file_path) and not os.path.isfile(file_path):
        print("Not Found : {}".format(file_path))
        raise FileNotFoundError

    if os.path.isdir(save_dir):
        save_dir = os.path.join(save_dir, os.path.basename(file_path))
    else:
        save_dir = file_path

    zip_file_name = "{}.zip".format(save_dir)

    print('zip file : {}'.format(zip_file_name))
    with zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) as z:
        if os.path.isfile(file_path):
            print(">>zipping....   {}".format(file_path))
            file_name = os.path.basename(file_path)
            z.write(file_path, file_name)
        else:
            for file_name in get_file_path(file_path):
                head, tail = file_name.split(os.path.join(file_path,'').replace(os.sep,'/'))
                print(">>zipping....   {}".format(file_name))
                z.write(file_name, tail)

    return zip_file_name

使い方

main.py
from zip import zipping

if __name__ == '__main__':
    file_path = "/sample/sample.jpg"
    file = zipping(file_path, "/tmp")
7
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?