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! Here you'll get experience
opening a text file, printing its contents to the shell and, finally,
closing it.
This exercise is part of the course
Importing Data in Python
Exercise instructions
- Open the file
moby_dick.txtas read-only and store it in the variablefile. 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 methodread()to the objectfile. - Check whether the file is closed by executing
print(file.closed). - Close the file using the
close()method. - Check again that the file is closed as you did above.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Open a file: file
file = open(____, ____)
# Print it
print(____)
# Check whether file is closed
print(file.closed)
# Close file
# Check whether file is closed