This session will introduce the idea of “persistent” programs that keep data in permanent storage, show how to use different kinds of permanent storage, like files and databases.

What is I/O?

I/O in computer science means Input/Output.

Q. Why is I/O so important?

Q. Can you give some exmples of I/O?

Q. What is the difference between Synchronous and Asynchronous I/O?

Files

Most of the programs we have seen so far are transient in the sense that they run for a short time and produce some output, but when they end, their data disappears. If you run the program again, it starts with a clean slate.

Other programs are persistent: they run for a long time (or all the time); they keep at least some of their data in permanent storage (a hard drive, for example); and if they shut down and restart, they pick up where they left off.

Examples of persistent programs are operating systems, which run pretty much whenever a computer is on, and web servers, which run all the time, waiting for requests to come in on the network.

One of the simplest ways for programs to maintain their data is by reading and writing text files. We have already seen programs that read text files; in this chapter we will see programs that write them.

An alternative is to store the state of the program in a database. In this chapter I will present a simple database and a module, pickle, that makes it easy to store program data.

Reading and writing files

To write a file:

fout = open('output.txt', 'w')

If the file already exists, opening it in write mode clears out the old data and starts fresh, so BE CAREFUL! If the file doesn’t exist, a new one is created.

line1 = "How many roads must a man walk down\n"
fout.write(line1)
line2 = "Before you call him a man?\n"
fout.write(line2)
fout.close()
# If you don’t close the file, 
# it gets closed for you when the program ends.

Exercise 01

Modify the function sed that takes as arguments a pattern string, a replacement string, and two filenames; it should read the first file and write the contents into the second file (creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced with the replacement string.

Filenames and paths

Files are organized into directories (also called “folders”). Every running program has a “current directory”, which is the default directory for most operations. For example, when you open a file for reading, Python looks for it in the current directory.

The os module provides functions for working with files and directories (“os” stands for “operating system”). os.getcwd returns the name of the current directory:

import os
cwd = os.getcwd() 
# cwd stands for “current working directory”. 
print(cwd)

os.path provides other functions for working with filenames and paths.

os.path.abspath('output.txt')
os.path.exists('output.txt')
os.path.isdir('output.txt')
os.path.isdir('/exercises')
os.path.isfile('output.txt')
os.listdir(cwd)

To demonstrate these functions, the following example “walks” through a directory, prints the names of all the files, and calls itself recursively on all the directories.

def walk(dirname):
    """Prints the names of all files in 
    dirname and its subdirectories.

    dirname: string name of directory
    """
    for name in os.listdir(dirname):
        path = os.path.join(dirname, name)

        if os.path.isfile(path):
            print(path)
        else:
            walk(path)

os.path.join takes a directory and a file name and joins them into a complete path.

The os module provides a function called walk that is similar to this one but more versatile.

def walk2(dirname):
    """Prints the names of all files in 
    dirname and its subdirectories.

    dirname: string name of directory
    """
    for root, dirs, files in os.walk(dirname):
        for filename in files:
            print(os.path.join(root, filename))

Catching exceptions

A lot of things can go wrong when you try to read and write files. If you try to open a file that doesn’t exist, you get an IOError:

fin = open('bad_file')

If you don’t have permission to access a file, you will get a PermissionError. If you try to open a directory for reading, you get an IsADirectoryError.

To avoid these errors, you could use functions like os.path.exists and os.path.isfile, but it would take a lot of time and code to check all the possibilities (if “Errno 2” is any indication, there are at least 21 things that can go wrong).

It is better to go ahead and try—and deal with problems if they happen—which is exactly what the try statement does. The syntax is similar to an if...else statement:

try:    
    fin = open('bad_file')
except:
    print('Something went wrong.')

Python starts by executing the try clause. If all goes well, it skips the except clause and proceeds. If an exception occurs, it jumps out of the try clause and runs the except clause.

Handling an exception with a try statement is called catching an exception. In this example, the except clause prints an error message that is not very helpful. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.

Databases

A database is a file that is organized for storing data. Many databases are organized like a dictionary in the sense that they map from keys to values. The biggest difference between a database and a dictionary is that the database is on disk (or other permanent storage), so it persists after the program ends.

The module dbm provides an interface for creating and updating database files. It is the smiplest databse module. I do not recommend it as a database solution for future project.

Exercise 02

  1. Read db_demo.py to learn how to create a database using dbm module, how to insert data and how to close the database.
  2. Read sqlite3_demo.py to learn how to access a database with SQL query language using sqlite3 module.

Pickling

A limitation of dbm is that the keys and values have to be strings or bytes. If you try to use any other type, you get an error.

The pickle module can help. It translates almost any type of object into a string suitable for storage in a database, and then translates strings back into objects.

pickle.dumps takes an object as a parameter and returns a string representation (dumps is short for “dump string”):

import pickle
t = [1, 2, 3]
print(pickle.dumps(t))

The format isn’t obvious to human readers; it is meant to be easy for pickle to interpret. pickle.loads (“load string”) reconstitutes the object:

t1 = [1, 2, 3]
s = pickle.dumps(t1)
t2 = pickle.loads(s)
print(t2)
t1 == t2
t1 is t2

Writing modules

Any file that contains Python code can be imported as a module. For example, suppose you have a file named wc.py with the following code:

def linecount(filename):
    count = 0
    for line in open(filename):
        count += 1
    return count

print(linecount('wc.py'))

If you run this program, it reads itself and prints the number of lines in the file, which is 7. You can also import it like this:

>>> import wc
7

Now you have a module object wc:

>>> wc
<module 'wc' from 'wc.py'>

The module object provides linecount:

>>> wc.linecount('wc.py')
7

So that’s how you write modules in Python.

The only problem with this example is that when you import the module it runs the test code at the bottom. Normally when you import a module, it defines new functions but it doesn’t run them.

Programs that will be imported as modules often use the following idiom:

if __name__ == '__main__':
    print(linecount('wc.py'))

__name__ is a built-in variable that is set when the program starts. If the program is running as a script, __name__ has the value '__main__'; in that case, the test code runs. Otherwise, if the module is being imported, the test code is skipped.

Exercise 03 (optional)

In a large collection of MP3 files, there may be more than one copy of the same song, stored in different directories or with different file names. The goal of this exercise is to search for duplicates.

  1. Write a program that searches a directory and all of its subdirectories, recursively, and returns a list of complete paths for all files with a given suffix (like .mp3). Hint: os.path provides several useful functions for manipulating file and path names.

  2. To recognize duplicates, you can use md5() to compute a a hash for each files. If two files have the same hash, they probably have the same contents. https://docs.python.org/3/library/hashlib.html