How do you write a line at the beginning of a file in python?

In modes 'a' or 'a+', any writing is done at the end of the file, even if at the current moment when the write() function is triggered the file's pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners.

1st way, can be used if there are no issues to load the file into memory:

def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

2nd way:

def line_pre_adder(filename, line_to_prepend):
    f = fileinput.input(filename, inplace=1)
    for xline in f:
        if f.isfirstline():
            print line_to_prepend.rstrip('\r\n') + '\n' + xline,
        else:
            print xline,

I don't know how this method works under the hood and if it can be employed on big big file. The argument 1 passed to input is what allows to rewrite a line in place; the following lines must be moved forwards or backwards in order that the inplace operation takes place, but I don't know the mechanism

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

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,

import os


def prepend_line(file_name, line):
    """ Insert given string as a new line at the beginning of a file """
    # define name of temporary dummy file
    dummy_file = file_name + '.bak'
    # open original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # Write given line to the dummy file
        write_obj.write(line + '\n')
        # Read lines from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)
    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)

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,

Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

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

# Insert a line before the first line of a file 'sample.txt'
prepend_line("sample.txt", "This is a first line")

Now the contents of the file are,

This is a first line
Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

A new line is added at the top of file.

Advertisements

Insert multiple lines at the top of a file

Suppose we have a list of strings,

list_of_lines = ['Another line to prepend', 'Second Line to prepend',  'Third Line to prepend']

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,

[ prepend_line("sample.txt", line) for line in list_of_lines ]

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.

import os

def prepend_multiple_lines(file_name, list_of_lines):
    """Insert given list of strings as a new lines at the beginning of a file"""

    # define name of temporary dummy file
    dummy_file = file_name + '.bak'
    # open given original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # 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 from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)

    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)

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,

This is a first line
Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

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

list_of_lines = ['Another line to prepend', 'Second Line to prepend',  'Third Line to prepend']

# Insert strings in a list as new lines at the top of file 'sample.txt'
prepend_multiple_lines("sample.txt", list_of_lines)

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

Another line to prepend
Second Line to prepend
Third Line to prepend
This is a first line
Hello this is a sample file
It contains sample text
Dummy Line A
Dummy Line B
Dummy Line C
This is the end of file

The complete example is as follows,

import os


def prepend_line(file_name, line):
    """ Insert given string as a new line at the beginning of a file """
    # define name of temporary dummy file
    dummy_file = file_name + '.bak'
    # open original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # Write given line to the dummy file
        write_obj.write(line + '\n')
        # Read lines from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)
    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)


def prepend_multiple_lines(file_name, list_of_lines):
    """Insert given list of strings as a new lines at the beginning of a file"""

    # define name of temporary dummy file
    dummy_file = file_name + '.bak'
    # open given original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # 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 from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)

    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)


def main():
    print('*** Insert a line at the top of a file ***')

    # Insert a line before the first line of a file 'sample.txt'
    prepend_line("sample.txt", "This is a first line")

    print('*** Insert multiple lines at the beginning of a file ***')

    list_of_lines = ['Another line to prepend', 'Second Line to prepend',  'Third Line to prepend']

    # Insert strings in a list as new lines at the top of file 'sample.txt'
    prepend_multiple_lines("sample.txt", list_of_lines)

if __name__ == '__main__':
   main()

How do you insert a line at the beginning of a file in Python?

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. ... .
Delete the original file..
Rename the temporary file as the original file..

How do you add a line to a file in Python?

Append data to a file as a new line in Python.
Open the file in append mode ('a'). Write cursor points to the end of file..
Append '\n' at the end of the file using write() function..
Append the given line to the file using write() function..
Close the file..

How do you print the first line of a file in Python?

“get first line of file python” Code Answer's.
f = open("test.txt", 'r').
variable = f. readline(1).
print(variable).

How do you write a text file line by line in Python?

The writelines() method write a list of strings to a file at once..
First, open the text file for writing (or append) using the open() function..
Second, write to the text file using the write() or writelines() method..
Third, close the file using the close() method..