Hugo Reyes
Hugo Reyes

Reputation: 83

How to add text to a file in python3

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

Answers (2)

Ender Look
Ender Look

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:

  1. We open the file an read all the lines making a list.
  2. We insert to the list the desired new line, using \n for a new line.
  3. We open the file again but this time to write.
  4. We write all the lines from the list.

But I wouldn't recommend this method, due it hight memory usage (if the file is big).

Upvotes: 1

Bryan Oakley
Bryan Oakley

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

Related Questions