File I/O

Files

Programs become more useful and interesting when they can interact with data that exists outside of the program. Almost all of the websites that you use store your data for their service in some kind of database or file system. That is how they can give you a persistent service. If we are going to be able to right persistent programs then we need to learn more about storing data. Databases are more of an advanced concept but for right now, the file system will do just fine.

Reading and Writing Files

Python makes interacting with files very simple. The built-in open() function provides us with a way to get a file object we can use.

file_obj = open('filename', 'r')

The open() function takes a filename (string) and a mode (string) and returns a file object.

The modes you give it allow you to do different things with the file object. Below is a table of what is possible:

Mode

Capability

r

read

w

write

a

append to file

r+, w+, a+

read & write

b

binary

Please read the documentation for more information on the modes. To avoid messing things up you typically don't want to open a file with more permissions than you need. It's up to you though what you decide.

Now that you have a file object, you can read from and write to the file you opened (assuming you used the appropriate mode). The File Object has many functions that can let you do a lot of complex operations but the simple ones you should know about are: read(), readline(), readlines(), write(), writelines(), and close(). The read functions ending in ...line(s) read the file and separate each line (using the newline character '\n'). writelines() takes a list and writes each element in the list as a separate line. These are really handy helper functions that you can use to avoid writing a for loop to read and write files.

One thing you should always remember when dealing with files is that you should always close them when you are finished. If you fail to close a file, then you are taking up resources on the computer and other programs might fail because you are a hog.

The With Block

Since it can sometimes be a huge pain to remember to close resources Python has created a special block that will close resources when the block ends. The with block lets you open a file and use it to do whatever you want and then will close the file for you when you're finished.

with open('filename', 'r') as f:
  lines = f.readlines()

Remember the scoping rules for lines since it is within the with block. If an error were to occur while opening the file, then lines would not be declared. You can get around that by declaring lines outside of the block.

lines = None
with open('filename', 'r') as f:
  lines = f.readlines()

You could then catch any file I/O errors using a try/except block.

lines = None
try:
  with open('filename', 'r') as f:
    lines = f.readlines()
except IOError as e:
  print(str(e))

for line in lines:
  recite(line)

Last updated