Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Retrieving Text From a File

00:00 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.

00:25 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.

00:38 That’s because .write() doesn’t automatically append the newline character, so you get to decide whether to use it or not by either including or not including a line feed in your string.

00:50 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 file.seek() with 0 as an argument, which indicates the character offset.

01:08 This will let you read the file contents again from the beginning. You can jump to any index you like—for example, 5and reading will start from that offset and go to the end of the file.

01:26 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:45 Now you’re getting only the first five characters. Calling the same method again will yield a different result.

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.

02:11 Here, 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.

02:39 That was a lot to take in. So why don’t you take a quick break now and continue in the next lesson?

Become a Member to join the conversation.