8.7 Reading and writing files
The file src/examples/sonnet-18.txt
contains the text of Shakespeare’s Sonnet 18. The following code sequence opens the file for
reading as text, reads the file into content
, closes the file, and prints the
string content
.
input_file = open("src/examples/sonnet-18.txt", "r")
content = input_file.read()
input_file.close()
print(content)
Shall I compare thee to a summer's day?
Thou art more lovely and more temperate.
Rough winds do shake the darling buds of May,
And summer's lease hath all too short a date.
Sometime too hot the eye of heaven shines,
And often is his gold complexion dimmed;
And every fair from fair sometime declines,
By chance, or nature's changing course, untrimmed;
But thy eternal summer shall not fade,
Nor lose possession of that fair thou ow'st,
Nor shall death brag thou wand'rest in his shade,
When in eternal lines to Time thou grow'st....