How to Append Text or Lines to a Text File in Python?

By Hardik Savani October 30, 2023 Category : Python

Hi Dev,

In this tutorial, you will discover how to append text in text file python. It's a simple example of how to add string to text file python. you'll learn python append text to text file. you'll learn python edit text file.

If you have an existing text file and you want to append some text or lines to the file in python then I will give you a very simple example for an editing a text file. we will take readme.txt file and append some text on it. we will use open() with "a" option. so let's see the below example.

You can use these examples with python3 (Python 3) version.

Example 1:

main.py

# append text on existing text file
with open("readme.txt", 'a') as f:
    f.write('New text file content line!')
  
print("New text file created successfully!")

Output:

It will append above line readme.txt file.

Hi ItSolutionstuff.com!
New text file content line!

I hope it can help you...

Tags :
Shares