PYTHONファイル操作
データを処理するとき、テキストファイルを編集する必要が生じることが多く、手動編集は退屈で時間がかかります。Pythonを使用してバッチ処理を実行する方がはるかに簡単です。
コード
import re
import os
def alter(file,file1,old_str,new_str):
file_data =""
with open(file,"r") as f:
for line in f:
if old_str in line:
line = line.replace(old_str,new_str)
file_data +=line
with open(file1,"w") as f:
f.write(file_data)
alter("first.info","second.info","str1","str2")
コード分析
これfirst.info(file)
は、元々変更が必要なファイルを
second.info
指します。保存されたファイルを
str1
指します。変更が必要なファイルに表示される文字列を指します。
str2
置換に使用される文字列を指します。