How to append a newline to a file in Python

To append a newline to the end of a file, write a line break statement (\n) after the content of the file then add the new content.

 

To demonstrate this, let's open a file inside a with statement, then write a line break then append another line of content to the file.

 

new_line = 'New line to add\n'

with open('file.txt', 'a') as file:
   file.write('\n')
   file.write(new_line)
file.txt
Some existing content
New line to add

 

In the example the file is opened in append (a) mode then content is appended to the file object using the .write() method. Append mode preserves all the existing content in the file and adds new content at the end of it.