Python

Python 3 Write Text to File Example – Open And Close Files Too

This post shows how to write text to files using Python 3. It involves opening or creating a file, writing texts, and closing it. We used Python 3.7.0 for the example.

Opening a File for Writing

In Python, before we can write to or read from a file, we need to open it. If the file doesn’t exist, we can specify to create it or not, especially when writing to it. Consider the Python codes below. Also, we can append a file by writing additional text to it. Meaning the previous content would still be there.

Open File to Write In Python

To open a file to write text in Python, we use the open function. Generally, it accepts two arguments — first, the file name, including the path. Second, the mode Python uses dictates what subsequent operations are valid.

In line 1, we open a file always_new_contents.txt in the current directory with wt mode. The second argument means to create the text file if it didn’t exist. Otherwise, use an existing text file with the same file name. Moreover, the mode makes Python override any content the text file had. Consider the following output.

If we rerun the codes, the text file will have the same content as before.

Open File to Append With Text

When our codes always override the content of a text file, we lose the content the file had. Therefore, sometimes it is better to append by text file content with new data. Let us say we have another file that has the following content.

We would want to keep the original content plus any new text we may have added. Consider the following codes. In line 1, we are using the same Python open function but passing a different second argument at.

When we run the codes,  Python generates the following new content.

If we rerun the codes, Python adds the same set of texts creating duplicate lines.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like