Skip to content

Python write to file new line

  • by

Use “\n” to write to file a new line in Python. To write a string to a file on a new line every time.

  1. Open the file in writing mode.
  2. Append a newline (\n) character to the end of each string.
  3. Use the file.write() method to write the lines to the file.
file.write("My String\n")

Note: Use “a” for append or write “r+” which is a read more combined with write more. Using “w”, erases the existing contents of the fil. Read more…

Python writes to file a new line example

A simple example code used the with statement to open the file in reading mode.

with open('example.txt', 'w', encoding='utf-8') as my_file:
my_file.write('first line' + '\n')
my_file.write('second line' + '\n')
my_file.write('third line' + '\n')

Output:

Python writes to file a new line example

In the following code, we will open a file named ‘demo.txt‘ and write two lines of text in it.

lines = ['Hello', 'Welcome!']
# Opening the file in write mode
f = open("demo.txt", "w")
for line in lines:
# Writing a new word into the file
  f.write(line)
  f.write("\n")
# Closing the file
f.close()

Do comment if you have any doubts or suggestions on this Python 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