Coding 204: Reading data from a file using Python

In this Learning Lab you will learn how to read data from a file using Python.

Objective

Completion Time: 15 minutes

  • Understand how to read data from a file
  • Understand the different modes that you can use when opening a file
  • Understand how to read JSON from a file

Prerequisites

Python

  • To run the code samples, you need to have Python 3 installed on your machine.
  • If you are working on a DevNet Learning Lab PC at a DevNet event, Python 3.4.2 is already installed.
  • See BYOD section above for how to install Python on your own machine.

Step 1. Introduction

In the Coding 203: Getting input from a user in Python learning lab, we learned how to get input from the user using the keyboard.

Another common way to get input is to read data from a text file.

Python makes this operation really easy.

Let's say we have a text file called myfile.txt. and it contains the following


This is the first line. Absolutely, the first line.
This is the second line. Yep, this is the second line.

We can read all of the data from this file and print it to the screen using the following statement.

# This line opens the file and creates an object called my_file_object that holds the reference to the file
my_file_object = open("my-file.txt", "r")

# read() reads in the entire file.  In this line of code, we read in the contents of the file and print it to the screen.
print (my_file_object.read())

Fairly simple, right? Let's try some examples.