LoginSignup
6
4

More than 5 years have passed since last update.

ファイル内文字列一括変換

Last updated at Posted at 2018-07-03

あるディレクトリにある複数ファイルが対象。
ファイル内の文字列を一括で変換したいとき用の.py です。
※対象ファイルを直接編集するので、バックアップをとってから使ってください!!!

使用例)

対象ファイル.txt
I'll be back !
I'll be back !
I'll be back !

    ↓

対象ファイル.txt
I'm back !
I'm back !
I'm back !

コード)

以下、例を処理した時のもの。

mojiReplace.py
 # -*- coding: utf-8 -*-
import glob

#対象ディレクトリの指定
path = "/home/../dir/"

beforeWord = 'll be'
afterWord = 'm'

#テキストファイルのPATHを取得
files = glob.glob(path + "*.txt")

for file in files :
    print("target : " + file)
    #対象ファイルの読み込み
    with open(file, "r") as f :
        sent = [ row.replace(beforeWord, afterWord) for row in f ]
    #書き込み    
    with open(file, "w") as f :
        f.writelines(sent)

以上!

2018/7/5 : コードのいらない部分を修正しました。

6
4
2

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