【DTP作業効率化】Office系ファイルに配置された画像を取り出すPython
エクセル、ワード、パワーポイントのファイルに画像が貼り付けられてクライアントから入稿されることがよくある。
そういうファイルは拡張子を「zip」にした後、解凍して「media」のフォルダから取り出す方法がありますが、1回でも面倒なこの作業、ファイルが何個もあったらひたすら面倒。
下記のpythonはOffice系ファイルから画像を取り出します。
このnoteというサイトはアプリケーションファイルもアップロードできることに気が付きました。一番下にMac用、Windows用のアプリケーションファイルをつけています。
import zipfile
import re
import tkinter
import os
from tkinter import filedialog
root = tkinter.Tk()
root.withdraw()
files = tkinter.filedialog.askopenfilenames()
for file in files:
fileDir = os.path.dirname(file)
fileName = os.path.splitext(os.path.basename(file))[0]
print(fileDir)
# フォルダを作成
save_dir = os.path.join(fileDir, fileName)
os.makedirs(save_dir, exist_ok=True)
with zipfile.ZipFile(file) as zf:
for name in zf.namelist():
print(name)
reg = re.compile("media")
if reg.search(name):
# ファイルを保存
extracted_path = os.path.join(save_dir, os.path.basename(name))
with open(extracted_path, "wb") as f:
f.write(zf.read(name))
解説
アプリを実行。
ファイルを選択。新しいフォルダが作られます。新しいフォルダの名前は元のOffice系ファイルの名前と同じです。
この記事が気に入ったらサポートをしてみませんか?