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:
-
Make a directory, perhaps called file_examples.
-
In IDLE, select File→New Window and type (or copy and paste) the following:
First line of text Second line of text Third line of text -
Save this file in your file_examples directory under the name file_example.txt.
-
In IDLE, select File→New Window and type (or copy and paste) this program:
file = open('file_example.txt', 'r') contents = file.read() ...
Get Practical Programming, 2nd 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.