Read Starship Names (Solution)
00:12 More specifically, reading a file in Python isn’t all that different from writing to it. You need to first open it using the write mode, so you can initially repeat the same code that you just wrote.
You can assume this file exists, and you can open it using the familiar
with statement, but this time you want to open it for reading, so you’ll use the letter
"r" instead of the letter
"w" as the value for the
You can then print each line to the screen. Even though this looks correct, you should always verify your code through testing. So let’s save this file as a Python module named
exercise_01_02, and let’s run it.
At this point, you might remember it’s the
print() function that adds an extra newline character at the end of each line by default. We can disable it by specifying an empty string as the value for the
Indeed, that helps. Now that we’ve verified the code works as expected, we can think if there’s anything we can improve about it. For example, the
.readlines() method is greedy, which means that it loads the entire file and splits it into separate lines stuffed into a Python list.
In such a case, you can take advantage of the fact that file objects in Python are iterable themselves. If you iterate over the file without calling
.readlines(), then Python will keep feeding you with the next line from the file until there are no more lines or you decide to break out of the loop prematurely.
02:51 This should still produce the same result, but use much less memory, which can be especially helpful when you work with those larger files. But since the starships file is tiny, we can actually read it all at once into a Python string instead of a list of lines.
Become a Member to join the conversation.