5 ways to append to existing text file Python

In this post, we will learn 5 ways to append to existing text file Python with the help of examples. We will use the OS module, file write(), and print() method.

1. WITH statement to Append to existing text file Python


To append a new line to the existing file, the first step is to open a file in append mode ‘a’ or ‘ab’; in this mode, the writer cursor is positioned at the end of the file. The access mode controls the operation we have to perform on an opened file, by using “with the statement ( “with open(‘filename’, ‘a’) as file:”) it creates a new file if does not exist or when the file already exists append data at end of the file and return file object.

Syntax

with open('filename', 'a') as file:

Parameters

  • Filename: The name of the file we want to write at the given path.
  • mode: It controls what operation we are performing on opened file.

Existing file content:data.txt

welcome to devenum.com
How are you.

Python Program to append text to the existing file

with open("data.txt", "a") as file:
    
    file.write("Good Morning! ")

Output

Welcome to devenum.com
How are youGood Morning! 

Read-write CSV files in Python

2. Append to existing text file new line


To open a file in access mode ‘a’ and append data in newline will work well if the file already exists, when the file does not exist it create a new file and append a blank file at beginning of the line. In this example, a newline will and if file not already exists.

Python Program Example

with open("data1.txt", "a") as file:
   

    file.write("\n")
   
    file.write("Good Morning!\n ")

Output

Good Morning!

2.1 Append newline(\n) if file exist


In this example, To overcome the above issue we have opened a file in append mode ‘a+’ for reading and writing. let us understand the below steps of how to add a newline at end of the file either the new file exists or already exists.

Steps to append new line in existing file


  • Move the file read-write position at beginning of the file by using file.seek(0).
  • Read some contents of the file by using the file.read().
  • If the content length is greater than 0 then we will add a newline character(\n)
  • when the file does not exist will not append a new line character.

Python Program Example

with open("data1.txt", "a+") as file:  
   
    file.seek(0)   
   
    content = file.read(30)
    if len(content) > 0 :
      file.write("\n")
   
    file.write("Good Morinig!")

Output

Welcome to devenum.com
How are you
Good Morning! 

3. Print() to append to a file in Python


In this example, we have opened files in append file mode and used the print() method instead of write() method to append to a file in Python.

Python Program to append text to existing file

with open("data1.txt", "a+") as file:
 print('Good Morinig!', file=file)
   

Output

Welcome to devenum.com
How are you
Good Morning! 

4. OS module to Append to a text file


In this example, we are using the OS module to append to a text file in Python. We have moved the writing position at end of the file by using file.seek(0, os.SEEK_END) method.

Python Program to append text to existing file

import os 
with open("data1.txt", "a+") as file:
 
    file.seek(0, os.SEEK_END)
    file.write("thanks for visiting us")


Output

Welcome to devenum.com
How are you
Good Morning!thanks for visiting us

5. Append mutiple lines in existing text file


In this example, we are opening the file in access mode append “a+”.we are appending multiple list lines at end of the file by iterating a list and writing its content.

Steps to append multiple lines in an existing file


  • Set the Read-write position at beginning of the file by using the file. seek(0).
  • Read some contents of the file by using the file. read() and check its length
  • If the content length is greater than 0 then append_newline =True a newline character(\n) will append at end of the file else append_newline =False new line character not append at end of the file.
  • iterating over the list (list_contents) using for loop aInnd writing the content to file.

Python Program to append existing text file

list_contents = ['Hi!','thanks','for','visiting Us']
with open("data1.txt", "a+") as file:
  
  append_newline = False
  file.seek(0)   
   
  content = file.read(30)
  if len(content) > 0 :
    bool_append_newline= True
  for line in list_contents:
  
    if append_newline == True:
         file.write("\n")
    else:
        append_newline = True           
    file.write(line)
    

Output

Welcome to devenum.com
How are you
Thanks 
Hi!
for 
Visting US

Summary

In this post, we have learned 5 ways to append to existing text file Python with the help of examples.