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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.