1

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.

Evan_Nt
  • 75
  • 6
  • Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – SteapStepper69 Jun 12 '20 at 10:45

1 Answers1

0

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))
Atharva Kadlag
  • 302
  • 3
  • 15