3) File Input/Output Lesson

Python: Read File

7 min to complete · By Martin Breuss

After you've learned how to write information to a file, you'll now read that information back into your program. Reading from a file has a very similar structure to writing to a file and requires similar steps:

  1. Open an existing file
  2. Read the data from the file
  3. Close the file

Open a File with Python

First, you have to open the file. This time, you'll use the default read mode ("r"):

file_in = open("filecounts.txt", "r")

Read a File with Python

After creating a file object in read mode, you can use .read() to read the entire content of your file into memory:

contents = file_in.read()

This line of code saves the content of your file in the variable contents.

Practice Reading Files

  • Print out the value of contents.
  • What data type does contents have?
  • Which challenges do you expect if you try to work programmatically with this data?

Try to answer the questions posed above and take a moment to think it through. Write your thoughts in your notebook, and brainstorm some possible solutions.

Colorful illustration of a light bulb

Info: You'll learn about better ways to handle input data in just a bit.

Close a File with Python

After you're done reading the data from your file, you must again close the file, just like you did when writing to it:

file_in.close()

Keep in mind that you need to call the .close() method on the file object that you've opened. In this example, you named the file file_in, so that's also the name you need to use when closing the file.

Challenging File Contents

If you followed the instructions through the last few lessons, then you'll end up with a value of content that looks similar to this:

# OUTPUT
"{'': 8, '.csv': 2, '.md': 2, '.png': 11}\n{'': 8, '.csv': 2, '.md': 2, '.png': 11}\n"

It's a str value that shows the representation of two dictionaries separated by newline characters.

Now, what would you do if you wanted to get a total count of all the .png files that you ever had on your desktop?

If you wanted to tackle this challenge programmatically, then you'd have to write custom code to parse your string and extract the right kind of information.

String Manipulation Practice

  • Train your string manipulation skills and write a script that can parse this string input and convert it back into a list of dictionaries that you can use to access information.

You can do that, but there are better ways that allow for better generalization and will make your collaborators happier.

Especially if you are planning to use the data your script produces programmatically or together with other people, there is a better way to achieve good structure and reusability of your data.

Using Common File Formats

While any data you'll be writing could be represented as text or binary data, and you could write custom code to parse the data correctly, you can make your life much easier by using common file formats for data storage and data exchange.

3 Common File Formats

  1. .csv
  2. .xml
  3. .json

All three of these file formats are commonly used to store and retrieve information programmatically.

Python has modules to handle all of them. In this section, you'll learn to work with the CSV format because it is extremely common and human-readable.

Later in this course, you'll also get to know the JSON format in more detail, as you'll learn how to receive data from the Internet, and JSON is a common standard for data exchange over the Internet.

Summary: Read Files with Python

  • You can read data from a file using open() with the default read mode ("r"). To get the full content of a file, you next call .read() on the file object.
  • There are also other Methods of File Objects that you can use to read from a file object, for example, line-by-line.
  • To make it easier to retrieve the stored information and work with it, there are certain conventions around how to format data in a file.

Common File Formats

  1. CSV
  2. XML
  3. JSON