下面是例子是读取一个文件内容,并且改变其中满足正则的行,进行内容追加。
# use command : reWriteFile.py oldFileName.txt newFileName.txt
import re
import sys
param = sys.argv
if len(param) > 3:
sys.exit()
oldFile = param[1]
newFile = open(param[2], "w+")
with open(oldFile) as f2:
while True:
line = f2.readline() # read content line by line
v = re.match(r"(.*?(\'\d(\.\d)+\',))((\d+\,)+)(\".*\")", line) # use regrex to match the content needed to be changed
if v:
value = v .group(4)
temp = value.split(",")
maxCountNu = max(temp, key = temp.count) # in my example, to caculate the max count of one element in list
value += maxCountNu + ","
nFile.write((v .group(1) + value + v .group(6))) # write to new file
nFile.write("\n")
else:
nFile.write(line)
if not line: break
nFile.close()