Python - How To Write Line by Line to a File

ID : 405

viewed : 100

Tags : PythonPython File

vote vote


When learning to program, we must know how to work with files. We should know how to read data from a file, how to write data to a file, how to append data to a file, etc. This article will not focus on all the operations we can perform over files but learn how to write to a file line by line using Python.

Write to a File Line by Line Using Python

Suppose we have a bunch of strings that we have to write to a file. To write them line by line, we have to append an end-line character or \n at the end of each line so that the strings appear individually. Refer to the following code for the same.

data = [     "Hello World!",     "This is a Python program.",     "It will write some data to a file.",     "Line by line." ]  file = open("file.txt", "w")  for line in data:     file.write(line + "\n")      file.close() 

  • Related HOW TO?