Appendix K — Text File Operations

Python applications have access to their surrounding environment, including any files that may exist there.

In this chapter we will practice reading and writing text files, using the open function.

For these example, let’s consider the following textual message, which in this case is a multiline string:

message = """
Hello World!

This is a message.
"""

print(type(message))
print(message)
<class 'str'>

Hello World!

This is a message.

K.1 Writing Files

We can use the open function in “writing” mode ("w") to write text contents to file:

filepath = "my_message.txt"

with open(filepath, "w") as file:
    file.write(message)

Let’s break this down.

When using the open function, we pass the name (or the full path) of the file as the first parameter, then the “mode”, or the way in which we intend to open the file (i.e. reading or writing), as the second parameter.

Note

FYI: the with statement creates a context manager that allows us to open the file without explicitly closing it. The file will be closed when the indentation level resets back to the left margin.

Note

Here, file is an alias variable referencing the file object (technically a TextIOWrapper datatype). You can choose any variable name you like instead, just reference that same variable name inside the scope of the context manager when reading with the file’s read method, or writing with the file’s write method.

K.2 Reading Files

To verify the contents got written to file, let’s read the same file.

Here we are use the open function in “reader” mode ("r") to read the contents of the text file:

with open(filepath, "r") as file:
    contents = file.read()
    print(contents)

Hello World!

This is a message.

K.3 Removing Files

As we’ve seen, we can use the os module to detect and delete files:

import os

print(os.path.exists(filepath))
True
os.remove(filepath)

print(os.path.exists(filepath))
False