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