Get startedGet started for free

Importing entire text files

In this exercise, you'll be working with the file moby_dick.txt. It is a text file that contains the opening sentences of Moby Dick, one of the great American novels! In the video, you've seen you could open such a file using file = open('moby_dick.txt', mode='r'). You could then read from it with file.read() and close the file using file.close(). However, using context managers allows you to do this more effectively. In this exercise, you will gain experience opening a text file, printing its contents and, finally, closing it by using a context manager.

This exercise is part of the course

Introduction to Importing Data in Python

View Course

Exercise instructions

  • Open the file moby_dick.txt as read-only using a with statement and bind it to the variable file. Make sure to pass the filename enclosed in quotation marks ''.
  • Print the contents of the file to the shell using the print() function. As Hugo showed in the video, you'll need to apply the method .read() to the object file and print the result.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Open a file as read-only and bind it to file
with open('____', '____') as file:
  	# Print it
    print(____)
Edit and Run Code