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:
JavaScript
x
3
1
parameter1 = "some code..."
2
parameter2 = "some code..."
3
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.
JavaScript
1
8
1
with open('file.py', 'r') as file:
2
file_content = file.readlines()
3
4
file_content.insert(1,'parameter2="somecode..."n')
5
6
with open('file.py', 'w') as file:
7
file.write(''.join(file_content))
8