Skip to content

Python write to file line by line

Use \n to write to file line by line in Python. The \n will be translated automatically to os.linesep. This should be as simple as:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

Python writes to file line by line

A simple example code uses the open() function and add a parameter either “a” or “w”. To append content at the end of the file, use the “a” parameter. To overwrite any existing content in the file, use the “w” parameter.

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')
    the_file.write('Robo')

Output:

Python writes to file line by line

Python writes multiple lines to file

The writelines() method writes the items of a list to the file.

with open('data.txt', 'a') as f:
    line1 = "PS5 Restock India \n"
    line2 = "Xbox Series X Restock India \n"
    line3 = "Nintendo Switch Restock India"

    f.writelines([line1, line2, line3])

Output:

PS5 Restock India 
Xbox Series X Restock India 
Nintendo Switch Restock India

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading