Prev - #7 ASCII Table | Table of Contents | Next - #9 Chess Square Color

Exercise #8: Read Write File

File I/O, or file input/output, allows your programs to read and write data to files on the hard drive. This exercise covers just the basics of writing text to a file with Python code and then reading the text from the file you just created. File I/O is an important technique because it allows your programs to save data so that work isn’t lost when the program closes.

Exercise Description

You will write three functions for this exercise. First, write a writeToFile() function with two parameters for the filename of the file and the text to write into the file. Second, write an appendToFile() function, which is identical to writeToFile() except that the file opens in append mode instead of write mode. Finally, write a readFromFile() function with one parameter for the filename to open. This function returns the full text contents of the file as a string.

These Python instructions should generate the file and the assert statement checks that the content is correct:

writeToFile('greet.txt', 'Hello!\n')

appendToFile('greet.txt', 'Goodbye!\n')

assert readFromFile('greet.txt') == 'Hello!\nGoodbye!\n'

This code writes the text 'Hello!\n' and 'Goodbye!\n' to a file named greet.txt, then reads in this file’s content to verify it is correct. You can delete the greet.txt file after running these instructions program.

Try to write a solution based on the information in this description. If you still have trouble solving this exercise, read the Solution Design and Special Cases and Gotchas sections for additional hints.

Prerequisite concepts: text file reading and writing

Solution Design

Python’s built-in open() function returns a file object that you can use to read or write text from and to the file. You should call open() with the with statement, like with open(filename, mode) as fileObj:.

The valid arguments for the mode parameter are 'r' to read from text files, 'w' to write to text files, and 'a' to append (that is, write at the end of) to text files. If no mode argument is given, then the function defaults to read mode. Opening the file in write or append mode lets you call fileObj.write('text goes here'), which allows you to pass a string of text to write to the file. Otherwise, in read mode calling fileObj.read() returns the file’s contents as a string.

Special Cases and Gotchas

If you open a file in write mode and the file doesn’t exist, then a blank file is created. If the file does exist, it is overwritten with a blank file. Append mode, as opposed to write mode, adds text to the end of the file without destroying the original content.

Now try to write a solution based on the information in the previous sections. If you still have trouble solving this exercise, read the Solution Template section for additional hints.

Solution Template

Try to first write a solution from scratch. But if you have difficulty, you can use the following partial program as a starting place. Copy the following code from https://invpy.com/readwritefile-template.py and paste it into your code editor. Replace the underscores with code to make a working program:

def writeToFile(filename, text):

    # Open the file in write mode:

    with open(filename, ____) as fileObj:

        # Write the text to the file:

        ____.write(text)

 

def appendToFile(filename, text):

    # Open the file in append mode:

    ____ open(filename, ____) as fileObj:

        # Write the text to the end of the file:

        ____.write(____)

 

def readFromFile(filename):

    # Open the file in read mode:

    ____ ____(filename) as fileObj:

        # Read all of the text in the file and return it as a string:

        return ____.read()

The complete solution for this exercise is given in Appendix A and https://invpy.com/readwritefile.py. You can view each step of this program as it runs under a debugger at https://invpy.com/readwritefile-debug/.

Further Reading

You can learn about reading and writing files in Chapters 9 and 10 of my book, Automate the Boring Stuff with Python online at https://automatetheboringstuff.com/2e/.

Prev - #7 ASCII Table | Table of Contents | Next - #9 Chess Square Color