Nono.MA

Write Text to File with Python

OCTOBER 13, 2020

To write text to a file using Python, you can either append text or overwrite all existing contents with new text.

Appending text

To append text, open the file in append mode, write to it to add lines of text, and close it.

file = open('/path/to/file.txt', 'a') # 'a' is append-to-end-of-file mode
file.write('Adding text to this document.')
file.close()

Overwriting text

You can also write the entire contents of the files, overwriting any existing content using the w mode instead of a.

file = open('/path/to/file.txt', 'w') # 'w' is overwrite mode
file.write('This will override any existing content in the text to this document.')
file.close()

Line breaks

You can use \r\n or \n and other codes to add line breaks to your document.

file = open('/path/to/file.txt', 'w') # 'w' is overwrite mode
file.write('First line.\nSecond line.\nThird line.\n\nNono.MA')
file.close()
# file.txt
First line.
Second line.
Third line.

Nono.MA

CodePython