🐍

【Python】OS操作めも

2023/02/12に公開

記事について

pythonによるOS操作のコードを目的別にメモします。

動作環境

Python 3.9.7
JupyterLab 3.2.1

ファイル名の一括置換

replace_filename.py
import os
import glob

# 現在の作業ディレクトリ内のすべてのファイル名を取得
file_list = glob.glob('*')

# 置換する文字列を取得
old_string = input('置換前の文字列を入力してください: ')
new_string = input('置換後の文字列を入力してください: ')

# 各ファイル名に対して置換処理を実行
for file_name in file_list:
    if old_string in file_name:
        new_file_name = file_name.replace(old_string, new_string)
        os.rename(file_name, new_file_name)

ファイル内の特定の文字列を置換

replace_filecontent.py
import os
import glob

files = glob.glob('*.txt') # ここでは、.txt形式のファイルを対象とする
old_str = input('置換前の文字列を入力してください: ')
new_str = input('置換後の文字列を入力してください: ')

for file_name in files:
    with open(file_name, 'r') as f:
        file_content = f.read()
    file_content = file_content.replace(old_str, new_str)
    with open(file_name, 'w') as f:
        f.write(file_content)
    print(f'{file_name}の内容を置換しました')

Discussion