O'Reilly logo

Head First Python by Paul Barry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Files and Exceptions: Dealing with errors

image with no caption

It’s simply not enough to process your list data in your code. You need to be able to get your data into your programs with ease, too. It’s no surprise then that Python makes reading data from files easy. Which is great, until you consider what can go wrong when interacting with data external to your programs...and there are lots of things waiting to trip you up! When bad stuff happens, you need a strategy for getting out of trouble, and one such strategy is to deal with any exceptional situations using Python’s exception handling mechanism showcased in this chapter.

Data is external to your program

Most of your programs conform to the input-process-output model: data comes in, gets manipulated, and then is stored, displayed, printed, or transferred.

image with no caption

So far, you’ve learned how to process data as well as display it on screen. But what’s involved in getting data into your programs? Specifically, what’s involved in reading data from a file?

How does Python read data from a file?

It’s all lines of text

The basic input mechanism in Python is line based: when read into your program from a text file, data arrives one line at a time.

Python’s open() BIF lives to interact with files. When combined with a for statement, reading files is straightforward. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required