Exercise 15

Reading Files

You know how to get input from a user with input or argv. Now you will learn about reading from a file. You may have to play with this exercise the most to understand what’s going on, so do the exercise carefully and remember your checks. Working with files is an easy way to erase your work if you are not careful.

This exercise involves writing two files. One is the usual ex15.py file that you will run, but the other is named ex15_sample.txt. This second file isn’t a script but a plain-text file we’ll be reading in our script. Here are the contents of that file:

1   This is stuff I typed into a file.
2   It is really cool stuff.
3   Lots and lots of fun to have in here.

What we want to do is ...

Get Learn Python the Hard Way: A Deceptively Simple Introduction to the Terrifyingly Beautiful World of Computers and Data Science, 5th 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.