How to write a text file in Python

1 min

In Python you will often need to write text files to save anything that you might reuse in the future.

Writing a text file is as simple as reading it.

Just as reminder, I wrote an article about how to read a text file in Python.

How to read a text file in Python
How to read a text file using Python.

Writing the file

# We define our text content to be written in the file.
text_content = """Lorem ipsum dolor it samet

Some text on a different line

# We use open to open an instance of the file
with open("path/to/file.txt", "w") as file:
    file.write(text_content) # We write all the text content into the file

See the "w" where we tell python in which mode it should deal with the file.

Modes can be create/read/write or even append.

Here we have "w" which tells Python to write the file.

If the file is not created it will create it then write the text_content.