Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#15: Reading Text

                          << Previous Tutorial           Next Tutorial >>
On this page: reading from a file, open(), .readlines().

Get Started

Video Summary

  • Interactive IDLE session from this tutorial.
  • To open a text file within your code, use Python's built in open() function. Within the open() function, type a string containing the path of the location of your text file (in this case, it looks like open('C:/Users/mybringback/Desktop/pg16328.txt'), your location will of course look different). After opening your text file, you can tell Python what to do with it by defining it is a variable. For example, typing booktxt = book.readlines() will define "booktxt" as your text file and allow it to be recalled within your program on a readable line by line basis.
  • After defining this variable, simply typing booktxt will display your entire text file start to finish within your IDLE window. While this feature can be useful in other circumstances, oftentimes your text will be too long and unwieldy to be recalled in this manner, as is the case with the large text file used in this tutorial. In this case, you can also recall select lines from your text by placing the specific line number within brackets next to your variable. For example, booktxt[0] will recall the first line of the text from your file, which in the text we are using is formatting information.
  • To recall the length in words of your text file, type len(booktxt). For more information on the len() function, see Tutorial 11.

Learn More

  • If you are a Mac user, omit the drive letter "C:" from your file path. Mac's directory tree simply starts from "/", which is called the root.
  • It was not done in the tutorial, but a file object, once opened and processed, must be closed. In the tutorial, a good time to close would have been after book.readlines() was executed. It can be done by calling book.close().
  • There are more details to learn (and battle with) in dealing with files on your local drive. See this advanced topic page: "File Path and CWD".
  • There are additional reading methods that are handy. See "File Reading and Writing Methods" for details.

Explore

  • Anne Dawson has many sample scripts for File I/O. Search for "open". Note that she uses the "escaped backslash" style (see this page) of Windows file path reference.