Exploring Bioinformatics with Python

Reading from Files

Rough notes.

Open a file for reading with

    infile = open('name_of_file', 'r')

The 'r' indicates that we're opening the file to read. You can elide it.

Read one line from the file with the readline procedure.

    line = infile.readline()

The procedure returns a string that includes the carriage return at the end of the line. You may want to eliminate it.

Read the remaining contents of a file with the read procedure.

    contents = infile.read()

This also includes all of the carriage returns. In this case, you are more likely to want to keep them.

When you are done with a file, close it.

    infile.close()

This page was generated by Siteweaver on Thu Sep 10 10:32:56 2009.
The source to the page was last modified on Thu Sep 10 10:32:53 2009.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/ExBioPy/reading-files.html.

You may wish to validate this page's HTML

Samuel A. Rebelsky
rebelsky@grinnell.edu