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.
CodePudding user response:
You're causing ain infinite loop by inserting into the list that you're looping over.
Instead, add the lines to a new list.
with open('test1.spd', 'r ') as f:
newfile = []
for line in f:
newfile.append(line)
if '.DisplayUnit = du' in line:
newfile.append('.DisplayUnit = nl\n')
f.seek(0)
f.writelines(newfile)
f.truncate()
Note that you need to include the \n
at the end of the line, f.writelines()
doesn't add them itself.
Since you're not inserting into the list of lines in this version, there's no need to use readlines()
, just iterate over the file to read one line at a time.