zipfileモジュールでファイルを圧縮してみた

はじめに
Xでつぶやいた通り、Progateを進めている。
#今日の積み上げ
— 柴田浩貴 (@2021_shibata) July 20, 2024
平日は仕事で朝会があり、今日自分がやることをアウトプットする機会がある。
一方、休日はそのような機会がないため、Twitter(X)を再開したいと思った。#今日の積み上げ は、以下の通り。
・Progate > Pythonで業務を自動化しよう > 月次報告資料をまとめて圧縮しよう > 道場 pic.twitter.com/qiVN3NYx89
zipfileというPythonの標準ライブラリを使用している。
いまいち実感が持てていないので、自分の目で確かめたいと思った。
参考サイト

こちらの記事を参考にさせていただきました。
前提条件
以下のようなファイル構成。sample.zipはもともと存在しなかった。

最初に出したエラー
zip.pyを実行したら、SyntaxError: expected ‘:’ となってしまった。

3行目の末尾の : を書いていなかったのが原因。以下の画像は、エラー解消後。

次に出したエラー
IndentationError: expected an indented block after ‘with’ statement on line 3

4行目のzf.writeの処理を書いていなかったのが原因。
sample.textをsample.zipに圧縮することができた
すでに記述した画像を使用する。
以下の処理を書いて、

zip.pyを実行すると、

同階層にzipファイルが作成された。

処理について解説

1行目で、zipfileモジュールをインポートしている。
3〜4行目で、with文を使用。with文は、終了の処理を書く必要がない。
3行目のzipfile.ZipFile(‘sample.zip’, ‘w’) as zfでは、書き込みモードで、zfという名前のZipFileオブジェクトを生成している。
ZipFileの第一引数には、新規作成するZIPファイルのパスを指定する。
第二引数には、モードを指定する。今回は書き込みを指定した。
4行目では、zfに対してwriteメソッドを使用することで、ZIPファイルを生成している。引数に渡されたファイルがZIPファイルに変換される。
コメントを残す