I have several files and want to add some text to them (files are named as changed_1, changed_2, changed_3 and so on) in python. Here I copied a piece of my file:
$MeshFormat
2.2 0 8
3 1 "volume_1"
$EndPhysicalNames
I want to add line/s exactly after the 3rd line (3 1 "volume_1"). I have another variable named as n_iteration. If n_iteration is 2, I want to add 3 2 "volume_2" exactly after the 3rd line. If it is 3, I want to add 3 2 "volume_2" and 3 3 "volume_3" and so on. Finally I want to have my files changed and saved exactly like the input format but with these added lines (let's say n_iteration = 4):
$MeshFormat
2.2 0 8
3 1 "volume_1"
3 2 "volume_2"
3 3 "volume_3"
3 4 "volume_4"
$EndPhysicalNames
Point is that I want to do the same (adding these lines) for several files. I tried the following code but I was not successful. Firstly, it is doing the iteration over n_iteration rather than my files (it is making 4 outputs rather than i ones). I have three inputs but it is making four outputs which all are resulted from the last file (last i from the first for loop). It has also a problem for doing what I want (it adds new line differently in outputs):
from glob import glob
all_files = glob('changed_*')
for i in all_files:
with open(i, "r") as f:
data = f.readlines()
n_iteration = 4
for j in range(n_iteration,0,-1):
with open('new'+ str (j), "w") as f:
data.insert(2, ('3 ' + str(j) +' "volume_' + str(j) + '"\n'))
del data[2+n_iteration]
for c in data:
f.write(c)
In advance, I do appreciate any help.
n_iteration = 4). It gave me four files, which are all exported from the last file imported to algorithm in the first for loop. the first file is completely OK. Second one=$MeshFormat 2.2 0 8 3 2 "volume_2" 3 3 "volume_3" 3 4 "volume_4" 3 1 "volume_1". Third one=$MeshFormat 2.2 0 8 3 3 "volume_3" 3 4 "volume_4" 3 1 "volume_1". Fourth one =$MeshFormat 2.2 0 8 3 4 "volume_4" 3 1 "volume_1". So, I have four outputs rather than three ones and also they are wrong.