python读写Cpp源文件,txt文件

fileread = 'MTHINC.H'
filewrite = 'MTHINCw.H'
frd = open(fileread, 'r')
sth = frd.readlines()
# print(len(sth))
fwt = open(filewrite, 'w')
i = 0
for a in sth:
    i = i + 1
    if a.__sizeof__() == 50:
        fwt.write("Info<<\"Reaching line " + str(i) + " in file " + fileread + ".\"<<endl;\n")
    else:
        fwt.write(a)
#  succeed

以上脚本是读取和添加每一行的行号

以下脚本是从当前py文件的目录读取txt文件(列表),并添加行数和列数信息,添加括号

更改格式

import re
import os

cwdPath = os.getcwd()
print('Current directory is: ', cwdPath)
file_name_list = os.listdir(cwdPath)
print('Files\' names are: ', file_name_list)
reCom = re.compile(".*\.txt")
file_read_list = []
for file_name in file_name_list:
    is_match = reCom.match(file_name)
    if is_match:
        file_read_list.append(file_name)
print('Files to read are: ', file_read_list)
for fileread in file_read_list:
    filewrite = fileread + '.out'
    frd = open(fileread, 'r')
    GsPt_num = re.findall(r"\d+", fileread)
    GsPt_num = GsPt_num[1]
    print('number of gauss points is: ', GsPt_num)
    sth = frd.readlines()
    GsPt_num_file = re.findall(r"\d+", sth[0])
    GsPt_num_file = GsPt_num_file[0]
    print('number of gauss points in file to read is: ', GsPt_num_file)
    if GsPt_num == GsPt_num_file:
        ifModify = 0
    else:
        ifModify = 1
    if ifModify:
        fwt = open(filewrite, 'w')
        print('Number of Gauss Points is: ', sth.__len__())
        print('type of sth[0] is: ', type(sth[0]))
        sthRe = re.findall(r"\d+\.?\d*", sth[0])
        print('Number of scalar in each Gauss Point: ', sthRe.__len__())
        print('Type of sthRe[0] is: ', type(sthRe[0]))
        fwt.write(str(sth.__len__()) + ' ' + str(sthRe.__len__()) + "\n(\n")
        for oneLine in sth:
            outLine = '(' + oneLine[1:oneLine.__len__() - 1] + ')\n'
            fwt.write(outLine)
        fwt.write(')\n')
        frd.close()
        fwt.close()
        os.remove(fileread)
        os.rename(filewrite, fileread)
    else:
        frd.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

穿越前列线打造非凡yt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值