在文本文件中搜索和替换并保存更改
我正在尝试在文本文件中搜索模式并替换为另一个字符串。
我已在中打开了该文件。
R+
"模式并使用
Re.sub
用于替换文本。
Python输出窗口显示了所需的结果,但当我打开文本文件时没有任何更改。文本文件中不会替换要替换的字符串。
为什么会这样呢?
选择 | 换行 | 行号
- # !/usr/bin/python
- import os,re
- fName = r'LOCATION OF FILE'
- directory = os.path.dirname(fName)
- os.chdir(directory)
- fileName = os.path.basename(fName)
- print(fileName)
- o_File = open(fileName ,"r+")
- with o_File as readFile:
- for searchpattern in readFile:
- found_Pattern = re.search("\s*\'[\d]+\==*[\d]*\.*[\d]*\==*[\d]*\.*[\d]*\'*",searchpattern,re.IGNORECASE)
- if found_Pattern:
- found_Pattern_Pat = found_Pattern.group()
- print(value)
- fValue = re.sub(r'==(.+)==','==100==',found_Pattern_Pat)
- print(fValue)
- o_File.close()