2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonのPath.with_suffixはどこまで置き換える? .tar.gzを処理するときの落とし穴

2
Posted at

report.tar.gz の出力名を report.zip にしたくて Path(name).with_suffix(".zip") と書くと、結果は report.tar.zip です。with_suffix() が置き換えるのは最後の拡張子です。そこで拡張子を全部取ると、今度は report.v2.tar.gz の .v2 まで消す設計になりかねません。

以下は macOS 27.2.1、Python 3.11.14 のターミナルで実行した結果です。パスを文字列として観察しており、ファイル作成・上書き・アーカイブの変換は行っていません。

パスが持つ3つの値を読む

from pathlib import Path

for name in ["report.tar.gz", "report.v2.tar.gz", ".env", "README"]:
    path = Path("incoming") / name
    print(path.name, repr(path.suffix), path.suffixes, path.stem)
    print(" ", path.with_suffix(".zip").as_posix())
report.tar.gz '.gz' ['.tar', '.gz'] report.tar
  incoming/report.tar.zip
report.v2.tar.gz '.gz' ['.v2', '.tar', '.gz'] report.v2.tar
  incoming/report.v2.tar.zip
.env '' [] .env
  incoming/.env.zip
README '' [] README
  incoming/README.zip

with_suffix(".zip") では、拡張子のない .env や README にも .zip が付きます。ファイルの中身は別途検査します。

対象を .tar.gz に限定して出力名を作る

ここでは「小文字の .tar.gz で終わり、その手前に名前があるファイルだけを受け付ける」と決めます。path.name を対象にするため、親ディレクトリ名にドットがあっても切り落とす範囲は変わりません。

from pathlib import Path

def zip_destination(path):
    ending = ".tar.gz"
    if not path.name.endswith(ending) or path.name == ending:
        raise ValueError("expected a name ending in .tar.gz")
    return path.with_name(path.name.removesuffix(ending) + ".zip")

for name in ["incoming.v1/report.v2.tar.gz", "incoming.v1/report.gz", ".tar.gz"]:
    try:
        print(zip_destination(Path(name)).as_posix())
    except ValueError as error:
        print(f"{name}: {error}")
incoming.v1/report.v2.zip
incoming.v1/report.gz: expected a name ending in .tar.gz
.tar.gz: expected a name ending in .tar.gz

名前の後ろにある .tar.gz だけを removesuffix() で取り除き、with_name() で同じディレクトリの出力パスを作っています。.v2 はそのまま残ります。大文字の .TAR.GZ を受け付けるなら、その表記もテストに加えます。

AIの提案をレビューするときは、report.tar.gz だけで動作確認を終えず、残したいドットを含む report.v2.tar.gz と、拒否したい report.gz も渡します。この関数が返すのは出力候補のパスです。実際に書き込む処理では、同名の出力が既にあるときの扱いも決めておくと上書きを防げます。

参考資料は Python 3.11 の pathlib 公式ドキュメント です。


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?