Retrieving Text From a File
In this lesson, you’ll continue working with the same file that you created before. However, to make the explanation easier, let’s forget about using the
with statement for a moment and store the file object in a regular variable. So open it in the default read-only mode, remembering to specify the encoding, as always.
Now you can call
.read() without any arguments to read the entire file’s contents all at once. Notice that there was only one line of text in the file, even though you previously called
.write() two times.
If you now try calling
.read() the second time, then you’ll get an empty string because you’ve already reached the end of the file, and there’s no more content to read. However, you can move to the beginning of the file by calling
0 as an argument, which indicates the character offset.
But you don’t always have to read all the remaining characters from a file. Instead, you can request the maximum number of characters to read through an optional parameter to
.read(). Let’s rewind once again … and read up to five characters.
01:55 If you request more characters than what’s left in the file, then Python will return only the remaining ones without raising an error. At any time, you can ask Python to tell you the current offset from the beginning of the file.
13 is the total number of characters in the file, which means you’ve reached the end of it. Okay, earlier in this course, you learned that Python lets you read a text file line by line. To experiment with this, you have to close the current file, which has just one line of text, and open the other file with the Zen of Python that actually contains several lines.
Become a Member to join the conversation.