How to append text or lines to a file in python?

In this article, we will discuss how to append text or new lines to an existing file using python.


To append some text to a file in the end, we first need to open the file with access mode ‘a’,

file_object = open('sample.txt', 'a')

With file access mode ‘a’, open() function first checks if file exists or not. If the file doesn’t exist, then it creates an empty file and opens it. Whereas, if the file already exists then it opens it. In both cases, it returns a file object, and it has write cursor, which points to the end of the opened file. Now, if you write anything to the file using this file object, then it will be appended to the end.

Let’s use this to append text at the end of a file,

Append a text to file in Python

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

Hello this is a sample file
It contains sample text
This is the end of file

Now let’s append text ‘hello’ at the end of this file,

# Open a file with access mode 'a'
file_object = open('sample.txt', 'a')

# Append 'hello' at the end of file
file_object.write('hello')

# Close the file
file_object.close()

Contents of the file ‘sample.txt’ will be now,

Hello this is a sample file
It contains sample text
This is the end of filehello

We opened the file ‘sample.txt’ in append mode i.e. using access mode ‘a’. As cursor was pointing to the end of the file in the file object, therefore when we passed the string in write() function, it appended it at the end of the file. So, our text ‘hello’ gets added at the end of the file ‘sample.txt’.

Append a text to file in Python using ‘with open’ statement

We can open the file in append access mode i.e. ‘a’, using ‘with open’ statement too, and then we can append the text at the end of the file.
For example,

# Open a file with access mode 'a'
with open("sample.txt", "a") as file_object:
    # Append 'hello' at the end of file
    file_object.write("hello")

Contents of the file ‘sample.txt’ will be now,

Hello this is a sample file
It contains sample text
This is the end of filehellohello

Text ‘hello’ gets again added at the end of file ‘sample.txt’.
The main difference between this approach and the previous one was that we don’t need to close the file explicitly. It gets automatically closed when the execution block of ‘with statement’ ends.

In both the above examples, the text gets added at the end of the file. But as we can see, it is not appended as a new line. There might be scenarios when we want to add data to a file as a new line.
Let’s see how to do that,

Append data to a file as a new line in Python

Solution for this is a little tricky here. let’s start with the basic approach and then we will discuss drawback in it and see how to improve over it,

Basic approach

  • 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

Well this approach works fine if our file already exists and already has some data in it. But if the file doesn’t exist or file is empty then this approach will fail because contents of the file will be like this,

……………………..

New added Line

It first writes an empty line and then writes our line. But in this case, only appending a line was fine, we don’t need to write ‘\n’ before that.

So, our final approach should be like this,

  • Open the file in append & read mode (‘a+’). Both read & write cursor points to the end of the file.
  • Move read cursor to the start of the file.
  • Read some text from the file and check if the file is empty or not.
  • If the file is not empty, then append ‘\n’ at the end of the file using write() function.
  • Append a given line to the file using write() function.
  • Close the file

This solution will work fine in both scenarios. Let’s use this solution to append a newline at the end of the file.

Suppose we have a file ‘sample2.txt’ with following contents,

Hello this is a sample file
It contains sample text
This is the end of file

Append new line to the file,

# Open the file in append & read mode ('a+')
with open("sample2.txt", "a+") as file_object:
    # Move read cursor to the start of file.
    file_object.seek(0)
    # If file is not empty then append '\n'
    data = file_object.read(100)
    if len(data) > 0 :
        file_object.write("\n")
    # Append text at the end of file
    file_object.write("hello hi")

Contents of the file ‘sample2.txt‘ now,

Hello this is a sample file
It contains sample text
This is the end of file
hello hi

A new line is appended at the end of the file.

File access mode ‘a+’, creates opens the file for both read and writing. Also if file it doesn’t exist, and then it creates the file too.
Initially, both read & write cursors will be pointing to the end of the file. We moved the read cursor to the top of file to check if the file is empty or not.
If the file is not empty, then append ‘\n’ at the end of the file first and then append the line.

Let’s move the code to a separate function,

def append_new_line(file_name, text_to_append):
    """Append given text as a new line at the end of file"""
    # Open the file in append & read mode ('a+')
    with open(file_name, "a+") as file_object:
        # Move read cursor to the start of file.
        file_object.seek(0)
        # If file is not empty then append '\n'
        data = file_object.read(100)
        if len(data) > 0:
            file_object.write("\n")
        # Append text at the end of file
        file_object.write(text_to_append)

Let’s use this function to append one more line to a file that doesn’t exist

# Append one line to a file that does not exist
append_new_line('sample3.txt', 'This is first line')

Contents of the file ‘sample3.txt’ will be now,

This is first line

It confirms that it didn’t append ‘\n’ before writing a new line because the file was already empty.

Now let’s again append another line to the same file to check if it works fine,

# Append another line to a file that already exist & has some contents
append_new_line('sample3.txt', 'This is second line')

Contents of the file ‘sample3.txt’ will be now,

This is first line
This is second line

As file already exist and has contents too; therefore it first appended the ‘\n’ into the file and then our given line.

Append multiple lines to a file in Python

Suppose we have a list of string,

list_of_lines = ['First Line', 'Second Line', 'Third Line']

Now we want to append each element in the list as a line in the file. How to do that?

We could do that by calling above created function append_new_line() multiple times, but it is not an optimized solution because it will open and close the file for each element in the list.
We should open the file only once and append all the lines to it. To do that our algorithm should be like,

  • Open the file in append & read mode (‘a+’). Both read & write cursor points to the end of the file.
  • Move read cursor to the start of the file.
  • Read some text from the file and check if the file is empty or not.
  • If the file is not empty, then set appendEOL as True else False
  • Now for each element in the list
    • If its first element in List and appendEOL is False
      • Don’t append ‘\n’ at the end of the file using write() function.
    • Else
      • Append ‘\n’ at the end of thefile using write() function.
    • Append the element  to the file using write() function.
  • Close the file

Basically we don’t need to write first ‘\n’ if the file is empty.

A function to append multiple lines in a file is,

def append_multiple_lines(file_name, lines_to_append):
    # Open the file in append & read mode ('a+')
    with open(file_name, "a+") as file_object:
        appendEOL = False
        # Move read cursor to the start of file.
        file_object.seek(0)
        # Check if file is not empty
        data = file_object.read(100)
        if len(data) > 0:
            appendEOL = True
        # Iterate over each string in the list
        for line in lines_to_append:
            # If file is not empty then append '\n' before first line for
            # other lines always append '\n' before appending line
            if appendEOL == True:
                file_object.write("\n")
            else:
                appendEOL = True
            # Append element at the end of file
            file_object.write(line)

Now let’s use this function.
Suppose contents of file ‘sample3.txt’ is as follows,

This is first line
This is second line

We have a list of strings,

list_of_lines = ['First Line', 'Second Line', 'Third Line']

Append all the strings in this list as separate lines at the end of file ‘sample3.txt’

# Append strings in list as seperate new lines in the end of file
append_multiple_lines('sample3.txt', list_of_lines)

Now contents of file ‘sample3.txt’ is,

This is first line
This is second line
First Line
Second Line
Third Line

It appended all the strings in the given list as newlines in the file.

The complete example is as follows,

def append_new_line(file_name, text_to_append):
    """Append given text as a new line at the end of file"""
    # Open the file in append & read mode ('a+')
    with open(file_name, "a+") as file_object:
        # Move read cursor to the start of file.
        file_object.seek(0)
        # If file is not empty then append '\n'
        data = file_object.read(100)
        if len(data) > 0:
            file_object.write("\n")
        # Append text at the end of file
        file_object.write(text_to_append)

def append_multiple_lines(file_name, lines_to_append):
    # Open the file in append & read mode ('a+')
    with open(file_name, "a+") as file_object:
        appendEOL = False
        # Move read cursor to the start of file.
        file_object.seek(0)
        # Check if file is not empty
        data = file_object.read(100)
        if len(data) > 0:
            appendEOL = True
        # Iterate over each string in the list
        for line in lines_to_append:
            # If file is not empty then append '\n' before first line for
            # other lines always append '\n' before appending line
            if appendEOL == True:
                file_object.write("\n")
            else:
                appendEOL = True
            # Append element at the end of file
            file_object.write(line)

def main():

    print('Append a text to file in Python')

    # Open a file with access mode 'a'
    file_object = open('sample.txt', 'a')

    # Append 'hello' at the end of file
    file_object.write('hello')

    # Close the file
    file_object.close()

    print('Append a text to file in Python using "with statement"')

    # Open a file with access mode 'a'
    with open("sample.txt", "a") as file_object:
        # Append 'hello' at the end of file
        file_object.write("hello")

    print('Append data to a file as a new line in Python')

    # Open the file in append & read mode ('a+')
    with open("sample2.txt", "a+") as file_object:
        # Move read cursor to the start of file.
        file_object.seek(0)
        # If file is not empty then append '\n'
        data = file_object.read(100)
        if len(data) > 0 :
            file_object.write("\n")
        # Append text at the end of file
        file_object.write("hello hi")

    # Append one line to a file that does not exist
    append_new_line('sample3.txt', 'This is first line')

    # Append another line to a file that already exist & has some contents
    append_new_line('sample3.txt', 'This is second line')

    print('Append multiple lines to a file in Python')

    list_of_lines = ['First Line', 'Second Line', 'Third Line']

    # Append strings in list as seperate new lines in the end of file
    append_multiple_lines('sample3.txt', list_of_lines)


if __name__ == '__main__':
   main()

Output:

Append a text to file in Python
Append a text to file in Python using "with statement"
Append data to a file as a new line in Python
Append multiple lines to a file in Python

2 thoughts on “How to append text or lines to a file in python?”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top