Python: How to insert lines at the top of a file?

Inserting lines at the top of a file

Python: How to insert lines at the top of a file ?

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

Let’s see inserting a line at the top of a file :

We can’t insert a text directly anywhere in a file. To insert a line of text at the top, we can create a new file with same name as that of the original file and with same line of text at the top. We can implement this by taking a function.

How the function works?

  • First it accepts0 file path and new line that would be inserted as arguments
  • Then it creates & then open a new temporary file in write mode.
  • After creating Temporary file then add the new line that you want to insert in beginning in temporary file
  • After this open the original file in read mode and read the contents line by line
  • – For each line add/append that into the temporary file
  • After appending contents and new line to the temporary new file, delete the original file.
  • At last, rename the temporary new file as that of the original file.
import os
def prepend_singline(filename, line):
    # Code to insert new line at the beginning of a file
    # define a name to temporary file
    tempfile = filename + '.abc'
    # Open the available original file in read mode and temporary file in write mode
    with open(filename, 'r') as read_objc, open(tempfile, 'w') as write_objc:
        # Write new line to the temporary file
        write_objc.write(line + '\n')
        # Read lines from the original file and append them to the temporary file
        for line in read_obj:
            write_objc.write(line)
    # delete original file
    os.remove(filename)
    # Rename temporary file as that of the original file
    os.rename(tempfile, filename)
def main():
    # Insert new line before the first line of original file
    prepend_singline("document.txt", "This is a new line")
if __name__ == '__main__':
   main() 
Output :
This is a new line
Hi, welcome to document file
 India is my country
Content Line I
Content Line II
This is the end of document file

Insert multiple lines at the top of a file :

Let we have a list of strings and we want to add these to the beginning of a file. Rather than calling above used function and adding new line one by one to new file, we can create another function which accepts file name and list of strings as arguments.

Then we can add list of strings in the beginning of temporary new file by adding lines from list of strings and contents to new file and renaming the new file as the original one.

import os
def prepend_multlines(filename, list_asmult_lines):
    """Code to insert new list of string at beginning of a file"""
    # define a name to temporary file
    dummyfile = filename + '.abc'
    # Open the available original file in read mode and temporary file in write mode
    with open(filename, 'r') as read_objc, open(dummyfile, 'w') as write_objc:
        # Iterate over the given list of strings and write them to dummy file as lines
        for line in list_of_lines:
            write_obj.write(line + '\n')
        # Read lines one by one from the original file and append them to the temporary file
        for line in read_objc:
            write_objc.write(line)
    # delete original file
    os.remove(filename)
    # Rename temporary file as that of the original file
    os.rename(dummyfile, filename)
def main():
    list_asmult_lines = ['New Line A', 'New Line B',  'New Line C']
    # Insert string list as new line before the first line of original file
    prepend_multlines("document.txt", list_asmult_lines)
if __name__ == '__main__':
   main()    
Output :
New Line A
New Line B
New Line C
Hi, welcome to document file
 India is my country
Content Line I
Content Line II
This is the end of document file