mycpen

Mycpen

记录学习历程与受益知识
github
telegram
bilibili

05_Other- Pythonのopen関数を使用してファイルの内容を一括置換する

2023/02/06 更新#

VSCode は 特定のコンテンツを一括置換する 機能を統合しており、より便利になりました

image-20230206183933193

1. 前言#

jsd の無効化後、筆者は新しい画像ホスティングソリューションを使用する必要があり、記事の元の jsd 画像リンクを新しい画像アドレスに置換する必要があります

このようなスクリプトはインターネット上にたくさんありますが、すべておすすめです。例えば

2. スクリプトの内容#

ソースコードはこちらから:ファイルの一括変更(Python 版)

このスクリプトは再帰的な方法で、43〜46 行のディレクトリ以下のすべてのファイルを走査し、一括置換を行います

注意:

  1. 43〜46 行の走査するディレクトリを自身の状況に合わせて変更してください。47、48 行の置換する内容を変更してください
  2. スクリプトの 24 行目では、Markdown タイプのテキストファイルのみが変更されるように制限されています。他のタイプのテキストファイルを変更する場合は、拡張子を自分で変更して一致させる必要があります
  3. 実行する前に、元のファイルをバックアップしておいてください。エラーが発生した場合に復元できない可能性があります
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# ソースコードの参考  https://blog.csdn.net/qq_38150250/article/details/118026219

import os
import re

# ファイル検索 find . -name file_name -type f
# 検索関数:search_path 検索するルートパス 

# 記事のパスを取得
def search(search_path, search_result):
    # 現在のパスのすべてのファイルを取得
    all_file = os.listdir(search_path)
    # それぞれのファイルに対して
    for each_file in all_file:
        # ファイルがディレクトリの場合
        if os.path.isdir(search_path + each_file):
            # 再帰的に検索
            search(search_path + each_file + '/', search_result)
        # 検索対象のファイルの場合
        else:
            if re.findall('.*\.md$', each_file) == [each_file]:
            # パスを出力
                search_result.append(search_path + each_file)


# 置換 sed -i 's/old_str/new_str/'
# テキストの置換 replace_file_name 置換するファイルのパス、replace_old_str 置換する文字、replace_new_str 置換する文字
def replace(replace_file_name, replace_old_str, replace_new_str):
    with open(replace_file_name, "r", encoding = "UTF-8") as f1: 
        content = f1.read()
        f1.close()
        t = content.replace(replace_old_str, replace_new_str)
    with open(replace_file_name, "w", encoding = "UTF-8") as f2:
        f2.write(t)
    f2.close()


# 変更が必要な箇所
#path = 'E:/code_zone/.history/20220831_blog/source/_posts/'
path_list = [
    'E:/code_zone/hexo-source/source/_posts/',
    'E:/code_zone/hexo-source-butterfly/source/_posts/',
]
old_str = 'https://image.cpen.top/image/'
new_str = 'https://image.cpen.top/image/'

search_result = []

if __name__ == '__main__':
    result = []                 # ファイルのパスを格納する
    # デフォルトは現在のディレクトリ
    # path = os.getcwd()
    for path in path_list:
        search(path, result)    # 記事のパスを取得
    count = 0
    for file_name in result:
        replace(file_name, old_str, new_str)
        count += 1
        print("{} done  {}".format(file_name, count))

# コマンド
# python E:/code_zone/tools/python-replace/replace.py

3. 参考記事#

ソースコードはこちらから:ファイルの一括変更(Python 版)

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。