I have got a python file with lines in specific order and I’m trying to add/remove lines in specific place in the file and then save it as a new one.
For example:
parameter1 = "some code..." parameter2 = "some code..."
I would like to add an additional line(e.g. parameter3) between these lines and/or remove one of them.
Advertisement
Answer
Read the lines from file into a list. Then you can insert in or remove from that list, e.g.
with open('file.py', 'r') as file: file_content = file.readlines() file_content.insert(1,'parameter2="somecode..."n') with open('file.py', 'w') as file: file.write(''.join(file_content))