This post will discuss how to write to a file in Python.

1. Using open() function

A simple solution is to open the file in write mode ('w') using the built-in open() function, which opens it for writing after truncating it. The file is created if it does not exist. Here’s what the code would look like:

 
The above syntax explicitly closes the file handler with the close() function, and you might need to try-finally block for exception handling. It is good practice to use the with keyword, which automatically closes the file once it is done with, even when an exception is raised. Here’s an equivalent code using the with statement:

 
Alternatively, you can open the file 'w+' mode, which opens it for both reading and writing:

Using'a' mode

If you need to append text at the end of the file if it exists, you can open it in the append mode ('a'). The file is created if it does not exist.

 
The stream is always positioned at the end of the file in 'a' mode. Additionally, if you need to read text from the file, use the 'a+' mode.

2. Using pathlib module

With Python 3.4, you can also use the pathlib module. The Path.write_text() function opens the file in text mode, write data to it, and close the file.

3. Using io module

Another option is to use the io.open() function, which is an alias for the built-in open() function.

That’s all about writing to a file in Python.