Importing text files line by line
For large files, we may not want to print all of their content to the shell:
you may wish to print only the first few lines. Enter the .readline()
method,
which allows you to do this. When a file called file
is open, you can print
out the first line by executing file.readline()
. If you execute the same
command again, the second line will print, and so on.
In the introductory video, Hugo also introduced the concept of a context manager. He showed that you can bind a variable file
by using a context manager construct:
with open('huck_finn.txt') as file:
While still within this construct, the variable file
will be bound to open('huck_finn.txt')
;
thus, to print the file to the shell, all the code you need to execute is:
with open('huck_finn.txt') as file:
print(file.readline())
You'll now use these tools to print the first few lines of moby_dick.txt
!
This exercise is part of the course
Introduction to Importing Data in Python
Exercise instructions
- Open
moby_dick.txt
using thewith
context manager and the variablefile
. - Print the first three lines of the file to the shell by using
.readline()
three times within the context manager.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Read & print the first 3 lines
with open('moby_dick.txt') as ____:
print(____)
print(____)
print(____)