Given an input file data.dat
like this one:
# Some comment
# more comments
#
45.78
# aaa
0.056
0.67
# aaa
345.
0.78
99.
2.34
# aaa
65.7
0.9
I need to add different comments above each line that starts with an "# aaa
" so it looks like this:
# Some comment
# more comments
#
45.78
# cmmt1
# aaa
0.056
0.67
# another cmmt
# aaa
345.
0.78
99.
2.34
# last one
# aaa
65.7
0.9
I know a priori the number of "# aaa
" comments present in the data.dat
file, but not their positions.
I have a way to do it (see code below) but it is quite complicated and not at all efficient. I need to apply this code to hundreds of large files, so I'm looking for an efficient way to do this.
# Read file
with open("data.dat", mode="r") as f:
data = f.readlines()
# Indexes of "# aaa" comments
idx = []
for i, line in enumerate(data):
if line.startswith("# aaa"):
idx.append(i)
# Insert new comments in their proper positions
add_data = ["# cmmt1\n", "# another cmmt\n", "# last one\n"]
for i, j in enumerate(idx):
data.insert(j + i, add_data[i])
# Write final data to file
with open("data_final.dat", mode="w") as f:
for item in data:
f.write("{}".format(item))