Pythonでファイル内の行を検索して置換する

PYTHON3 チュートリアル

Pythonでファイル内の特定の文字列を検索して置換する方法

Pythonは、ファイル内の特定の文字列を検索して置換するための強力なツールを提供しています。この記事では、Pythonを使用してファイル操作を行う方法を詳しく解説し、具体的なサンプルコードを紹介します。

ファイルを読み込んで文字列を置換する基本的な方法

Pythonでは、ファイルを読み込み、文字列を検索して置換するために、まずファイルを開き、内容を取得する必要があります。その後、文字列を置換し、変更を保存します。以下に基本的な例を示します。

# ファイル内の特定の文字列を置換する基本的な例
def replace_string_in_file(file_path, target_string, replacement_string):
    # ファイルを読み込む
    with open(file_path, 'r', encoding='utf-8') as file:
        file_data = file.read()
    
    # 文字列を置換する
    new_data = file_data.replace(target_string, replacement_string)
    
    # 変更された内容をファイルに書き込む
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(new_data)

# 使用例
replace_string_in_file('example.txt', 'old_string', 'new_string')

このコードは、指定したファイル内の特定の文字列を新しい文字列に置換します。’example.txt’というファイル内の’old_string’を’new_string’に置換します。

正規表現を使用した高度な置換

正規表現を使用することで、より柔軟な検索と置換が可能になります。Pythonのreモジュールを使用して、正規表現による置換を行う方法を示します。

import re

# 正規表現を使用してファイル内の文字列を置換する
def replace_with_regex(file_path, pattern, replacement):
    # ファイルを読み込む
    with open(file_path, 'r', encoding='utf-8') as file:
        file_data = file.read()
    
    # 正規表現で置換する
    new_data = re.sub(pattern, replacement, file_data)
    
    # 変更された内容をファイルに書き込む
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(new_data)

# 使用例
replace_with_regex('example.txt', r'\bold_string\b', 'new_string')

この例では、r'\bold_string\b'という正規表現パターンを使って、完全一致する’old_string’を’new_string’に置換します。

複数のファイルに対する文字列置換

複数のファイルに対して同じ文字列置換を行う必要がある場合、Pythonのosモジュールを使用してディレクトリ内のすべてのファイルを処理することができます。

import os

# ディレクトリ内のすべてのファイルに対して文字列を置換する
def replace_in_multiple_files(directory, target_string, replacement_string):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            with open(file_path, 'r', encoding='utf-8') as file:
                file_data = file.read()
            
            new_data = file_data.replace(target_string, replacement_string)
            
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(new_data)

# 使用例
replace_in_multiple_files('example_directory', 'old_string', 'new_string')

このコードは、指定されたディレクトリ内のすべてのファイルに対して’old_string’を’new_string’に置換します。

まとめ

Pythonを使用すると、ファイル内の特定の文字列を簡単に検索して置換することができます。基本的な置換から正規表現を利用した高度な置換、さらには複数ファイルへの適用まで、さまざまな方法があります。これらの方法を活用して、効率的なファイル操作を行いましょう。

Pythonを使用してファイル内の特定の行を検索して置換するには、まずファイルを開いてその内容を読み込む必要があります。ファイルを開くには、`open()`関数を使用します。次に、ファイル内の各行を順番に読み込み、特定の条件を満たす行を見つけるために正規表現を使用することが一般的です。

Pythonの`re`モジュールを使用して正規表現を扱うことができます。`re`モジュールをインポートし、`re.sub()`関数を使用して置換を行います。この関数は、指定したパターンに一致する部分を指定した文字列に置換します。

以下は、ファイル内の特定の行を検索して置換するPythonのサンプルコードです。

“`python
import re

# ファイルを開く
with open(‘file.txt’, ‘r’) as file:
lines = file.readlines()

# 置換するパターンを定義
pattern = re.compile(r’特定のパターン’)

# 各行をチェックして置換
for i, line in enumerate(lines):
if pattern.search(line):
lines[i] = re.sub(pattern, ‘置換後の文字列’, line)

# 結果をファイルに書き込む
with open(‘file.txt’, ‘w’) as file:
file.writelines(lines)
“`

このコードでは、`file.txt`というファイルから特定のパターンに一致する行を検索し、その行を`置換後の文字列`で置換しています。最終的に、置換後の内容を元のファイルに書き込んでいます。

購読
通知
0 Comments
Inline Feedbacks
View all comments