4
3

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で特定キーワードを含むファイルのみを一括変換・コピーする方法

Posted at

概要

本記事では、指定したディレクトリ配下のMarkdown(.md)ファイルや画像ファイル(例:.png)について、
ファイル名に特定のキーワードが含まれるものだけを抽出し、

  • Markdownはdocx(Word)形式に一括変換
  • 画像ファイルはそのままコピー
    するPythonスクリプトの作り方を解説します。

補足: NotionからGoogle Docsへ移行する必要があり、Notionからエクスポートした.mdファイルを.docx形式に一括変換してGoogle Docsにインポートする、という実際の業務ニーズが背景にあります。

変換・コピー先は、任意の出力ディレクトリ配下のサブフォルダ(例:output/SelectedFiles/)にまとめて格納されます。

こんな人におすすめ

  • プロジェクトや会議ごとにファイルを整理・変換したい
  • ファイル名でフィルタリングして一括処理したい
  • 汎用的なバッチスクリプトの雛形が欲しい

ポイント

  • キーワードやフォルダ名は自由に設定可能
  • コマンドライン引数で柔軟にパス指定
  • 画像以外にも拡張可能

コード例

convert_md_to_docx.py という名前で保存してください。

import os
import subprocess
import shutil
import sys

def convert_files_by_keyword(input_folder, output_folder, keyword_list, subfolder_name="SelectedFiles"):
    target_folder = os.path.join(output_folder, subfolder_name)
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)
    for root, dirs, files in os.walk(input_folder):
        for file in files:
            file_path = os.path.join(root, file)
            rel_path = os.path.relpath(file_path, input_folder)
            safe_name = rel_path.replace(os.sep, '_')
            if any(keyword in file for keyword in keyword_list):
                if file.endswith('.md'):
                    docx_name = os.path.splitext(safe_name)[0] + '.docx'
                    docx_path = os.path.join(target_folder, docx_name)
                    subprocess.run([
                        'pandoc',
                        file_path,
                        '-o',
                        docx_path
                    ])
                    print(f'Converted: {file_path} -> {docx_path}')
                elif file.endswith('.png'):
                    img_name = safe_name
                    img_path = os.path.join(target_folder, img_name)
                    shutil.copy2(file_path, img_path)
                    print(f'Copied: {file_path} -> {img_path}')
            else:
                print(f'Skipped: {file_path} (No keyword in filename)')

if __name__ == '__main__':
    if len(sys.argv) < 4:
        print('Usage: python convert_md_to_docx.py <input_folder> <output_folder> <keyword1> [<keyword2> ...]')
        exit(1)
    input_folder = sys.argv[1]
    output_folder = sys.argv[2]
    keyword_list = sys.argv[3:]
    convert_files_by_keyword(input_folder, output_folder, keyword_list)

使い方

  1. 必要なパッケージ(pandoc)をインストール
    • macOS: brew install pandoc
    • Windows: 公式サイト からインストール
  2. スクリプトを保存
  3. コマンド例:
python convert_md_to_docx.py ./input ./output ProjectX Meeting
  • ./input … 検索対象のディレクトリ
  • ./output … 変換・コピー先のディレクトリ
  • ProjectX Meeting … ファイル名に含まれると対象となるキーワード(複数指定可)

解説

  • キーワードリストはコマンドライン引数で柔軟に指定できます。
  • サブフォルダ名SelectedFiles)も関数引数で変更可能。
  • 画像以外の拡張子もelifで追加可能。
  • ファイル名の重複を避けるため、元のパスを_で連結したファイル名にしています。

応用例

  • PDFや他の画像形式も同様に追加可能
  • サブディレクトリごとに分けて保存したい場合は、safe_nameの生成方法を工夫

まとめ

このスクリプトを使えば、特定のキーワードでファイルを一括抽出・変換・コピーできます。プロジェクトの自動整理やレポート作成の効率化にぜひご活用ください。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?