How to Append a New Line in a File using Python

In this tutorial, we’ll learn how to program "How to Append a New Line in a File Using Python." The objective is to safely and efficiently add a new line to an existing text file. This tutorial will walk you through the step-by-step process of appending a new line, ensuring that the file's integrity is maintained. A sample program will be provided to guide you through the implementation. So, let’s get started!

This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the proper way to append a new line to a text file. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. while True:
  2.     print("\n================= Append a New Line in a File =================\n\n")
  3.  
  4.  
  5.  
  6.     file1 = open("mytext.txt", "a")
  7.  
  8.     my_str=input("Enter a text: ")
  9.  
  10.     file1.write("\n")
  11.  
  12.     file1.write(my_str)
  13.  
  14.     file1 = open("mytext.txt", "r")
  15.  
  16.     print("\nOUTPUT: ")
  17.     print(file1.read())
  18.     print()
  19.     file1.close()
  20.  
  21.  
  22.    
  23.     opt = input("\nDo you want to try again?(yes/no): ")
  24.  
  25.     if opt.lower() == 'yes':
  26.         ret=False
  27.     elif opt.lower() == 'no':
  28.         ret=True
  29.         print("Exiting program....")
  30.     else:
  31.         print("Please enter yes/no:")
  32.         break
  33.  
  34.     if ret == False:
  35.         continue

The program allows the user to input a string, which is then appended as a new line to the file "mytext.txt." After adding the input, the program reads the file and displays its updated content, showing the new text along with any previously written content. The user is prompted to decide whether they want to add more text or exit the program. If the user chooses to add more, the process repeats; otherwise, the program ends, closing the file and printing a message confirming the exit.

Output:

There you have it we successfully created How to Append a New Line in a File using Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment