In this article, we will discuss how to insert single or multiple lines at the beginning of a text or CSV file in python.

How to insert a line at the top of a file

There is no direct way to insert text in the middle of a file. Therefore we have to create a new file with the new line at the top and then rename this file as the original file. We have created a function for that,

What does this function do?

  • It accepts a file path and line to be inserted as arguments
  • Create & open a temporary file in write mode.
  • Add the given line as first-line in the temporary file
  • Open the original file in read mode and read the contents of the file line by line
    • For each line append that into the temporary file
  • Delete the original file.
  • Rename the temporary file as the original file.

Let’s use this function to insert a line at the beginning of a file.

Suppose we have a file ‘sample.txt’ and its contents are,

Now add a new line ‘’This is the first line” at the top of the file,

Now the contents of the file are,

A new line is added at the top of file.

Insert multiple lines at the top of a file

Suppose we have a list of strings,

We want to add each string in the list as a new line in the file.

To insert multiple lines at the beginning of a file, we can call the above created function prepend_line() various times i.e. once for each line like this,

But that is not an efficient solution because it will open, close and move contents to a temporary file for each string/line in the list. So, let’s create a function that opens the file only once and also insert multiple lines at the top of file i.e.

This function accepts a file name and list of strings as arguments. Then add the strings in the list as newlines in a temporary file and then append the lines from the original file to the temporary file. In the end, rename the temporary file as the original file.

Let’s use this function,

Contents of the file ‘sample.txt’ are,

Insert strings in a list as new lines at the top of a file ‘sample.txt’

Now the Contents of the file ‘sample.txt’ are,

The complete example is as follows,

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.