Writing to a file with print()

We have seen that when we write to standard output with print() we can write floats and integers and let Python take care of the formatting. If you are happy with Python's formatting, you can use the same function to write to a file. Here is how:

x = 3.14159265
fp =  open("output","w")

In the open statement the "w" is required. Otherwise, Python assumes you are opening the file for reading. If the file doesn't exist, it is created. If it exists, its previous contents are deleted. The file=fp “keyword” argument of the print() function causes the output to be sent to the file instead of to standard output. This option is available only in Python 3. The close() statement should not be omitted. It is needed to be sure the file is completely written.