Reputation: 83
Let's say i have the following file,
dummy_file.txt(contents below)
first line
third line
how can i add a line to that file right in the middle so the end result is:
first line
second line
third line
I have looked into opening the file with the append option, however that adds the line to the end of the file.
Upvotes: 0
Views: 65
Reputation: 2401
with open("dummy_file.txt", 'r') as file:
lines = file.readlines()
lines.insert(1, "second line\n")
with open("dummy_file.txt", 'w') as output:
output.writelines(lines)
So:
\n
for a new line.But I wouldn't recommend this method, due it hight memory usage (if the file is big).
Upvotes: 1
Reputation: 385910
The standard file methods don't support inserting into the middle of a file. You need to read the file, add your new data to the data that you read in, and then re-write the whole file.
Upvotes: 0