Opening a File

When you want to write a program that opens and reads a file, that program needs to tell Python where that file is. By default, Python assumes that the file you want to read is in the same directory as the program that is doing the reading. If you’re working in IDLE as you read this book, there’s a little setup you should do:

  1. Make a directory, perhaps called file_examples.

  2. In IDLE, select FileNew Window and type (or copy and paste) the following:

     First line of text
     Second line of text
     Third line of text
  3. Save this file in your file_examples directory under the name file_example.txt.

  4. In IDLE, select FileNew Window and type (or copy and paste) this program:

     file = open(​'file_example.txt'​, ​'r'​)
     contents = file.read() ...

Get Practical Programming, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.