How to Append Data to a New Line in a File Using Python
Vaibhav Vaibhav
Feb 02, 2024
Python is a universal language when it comes to file reading and manipulation. Because of its easy-to-understand syntax and built-in features, performing complex tasks over files becomes a more straightforward task relatively with Python. This article will talk about how we can append new data to a new line while writing a file in Python.
Append Data to a New Line Using a New Line Character (\n
) in Python
A new line is represented using a new line character or \n
in programming languages such as Python or C++. While appending or adding new data to a file, we can add this character at the end of each line to add new data to a new line. Let us understand this with the help of an example.
data = ["Hello World", "Hello", "World", "Python is a Programming Language"]
file = open("sample.txt", "w")
for x in data:
file.write(x)
file.write("\n")
file.close()
A file by the name of sample.txt
will be created in the working directory, and the following will be the file’s content.
Hello World
Hello
World
Python is a Programming Language
Author: Vaibhav Vaibhav