I am trying to find edit a file using python. I need to add contents after specific lines. Following is my code:
with open('test1.spd', 'r+') as f:
file = f.readlines()
for line in file:
if '.DisplayUnit = du' in line:
pos = line.index('.DisplayUnit = du')
file.insert(pos + 1, '.DisplayUnit = nl')
f.seek(0)
f.writelines(file)
f.close()
The file has about 150K+ lines. The above code is taking forever to edit it. Any help to improve the performance? I am quite new to python.