3
1

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.

[python]テキストファイル内の文字列を置換する

Posted at

はじめに

たまーにあるテキストファイル内の文字列を特定の文字列に置換しないといけない作業を
pythonのスクリプトで実行出来るようにした。

ソース

  • 関数

  • read()はテキストファイルの内容をすべて文字列として読み込んでくれるとのこと。
replaceWordsInFile.py
def replaceWordsInFile(fileName, before, after):

    with open(fileName, encoding="utf-8") as f:
        data_lines = f.read()

    # 指定したファイルの文字列を置換する
    data_lines = data_lines.replace(before, after)

    # 置換後に同じファイル名で保存する
    with open(fileName, mode="w", encoding="utf-8") as f:
        f.write(data_lines)

  • 呼び出し側

main.py
import replaceWordsInFile 

replaceWordsInFile.replaceWordsInFile("./sample.txt", "10", "11")
  • サンプルファイル

sample.txt
Today, I became 10 years old.

Everybody celebrated me as 10 years old boy!

結果

sample.txt
Today, I became 11 years old.

Everybody celebrated me as 11 years old boy!

参考文献

【Python】文字列⇔文字コードの変換方法(UTF-8・Shift_JIS)
Pythonで既存のテキストファイルを書き換える方法
Pythonでファイルの読み込み、書き込み(作成・追記)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?