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

More than 1 year has passed since last update.

指定フォルダ配下の指定ファイルを再帰的に取得し置換する

Last updated at Posted at 2022-05-16

概要

Python初心者です。
指定フォルダ配下の指定ファイルを再帰的に取得し置換します。

import glob

CURL_FILE_NAME = "input.txt"
TARGET = ".\\test\\**\\" + CURL_FILE_NAME

TARGET_STR = "XXX "
REPLACE_STR = "XXX -i "

# 指定フォルダ配下の指定ファイルを再帰的に取得
for f in glob.glob(TARGET, recursive=True) :
    print(f)

    with open(f, 'r', encoding="utf-8") as r:
        data = r.read()
        # 置換
        new_data = data.replace(TARGET_STR, REPLACE_STR)

    # ファイル更新
    with open(f, 'w', encoding="utf-8") as w:
        w.write(new_data)

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