pythonでファイル内の文字を置換する方法
環境
・windows 10
・python 3.6
今回は111というutf-8のテキストファイル内のAAAという文字列をBBBという文字列に置換する。
#coding:utf-8
with open(r"C:\Users\I\Desktop\111.txt","r",encoding="utf-8") as file:
filedata=file.read()
#with openでファイルを開いて、勝手に閉じてくれる。
filedata=filedata.replace("AAA","BBB")
#replaceでPublishという文字列をDraftという文字列に置換してくれる。
with open(r"C:\Users\I\Desktop\111.txt","w",encoding="utf-8") as file:
file.write(filedata)
#"w"とwriteでは中身が全て上書きされる。