An Introduction to Python: File I/O

File I/O

Table of Contents

Let's do things with files!

File I/O in C/C++ required including several header files and defining a series of stream objects, or file objects. Python is similar, but opening files is a more basic function and generally much more straightforward. Let's create a file quickly and dump some text into, namely a list of names that we'll enter at the commandline.

Notice that we simply have to use the open command to open a file, and give it the "r" argument to open the file for reading. The value returned from this function is a file object, which we can use to read (or write, if we had also(instead of) specified the "w" flag). From there you can either read the entire file with a fileobject.read() command, or read a line at a time with readline()(what I usually use).

Now let's go over some useful utility functions:

Here is a more advanced example, which reads in the following file, "hw0grades.txt", which contains the current grades for the first (Zeroth) cs373 homework:

Now, since we know some basics of files, we can go ahead and read them a bit, and go ahead and compute somethings about my grade:

This example is a little more complicated, but it's definitely more real world. A very common use for Python is doing file and string parsing tasks like this. It's not as well known for this task as Perl, although it really is quite suitable for this sort of thing (and your chances of being able to maintain this code in the future is better).

Finally, I want to talk about pickling things. Python has a facility for compressing native objects into strings for transmission across the network, or to write to disk.

You might refer to this technique as a method of "Object Persistance" or something similar, and you'd be right. If you have data you'd like to save between sessions, like an objects personal state, just pickle it. This could be a simple way to create a basic file format for your programs datafiles, or it could enable faster crash recovery for a large program. You might even use it while playing at the commandline to save something temporarily.

There are quite a few modules besides Pickle that can be used to do this in Python, but Pickle is the fundamental building block for many of them. Larger projects with more data might decide to use Shelves, which are a lot like dictionaries that store pickled objects.

Follow along with this simple example, and remember that there is more to Pickling then what I've got below.


hello.py
Table of Contents