Python读取文件并修改文件内容后保存为新文件

下面是例子是读取一个文件内容,并且改变其中满足正则的行,进行内容追加。

# 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()

    原文作者:万万君
    原文地址: https://blog.csdn.net/devin_xin/article/details/105712717
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞