crew.txt sits in the mission folder, saved and safe. Now Rocket wants a different program to read it and greet each crew member by name.
His first try prints the names with a blank line after every one. "Why is it double spaced?" he asks. "I did not add any extra lines."
Raven looks at the file and then at the print. "What do you notice?" she asks. "Each line in the file already ends with a newline. Then print adds one more."
Nova highlights the invisible newline at the end of each line. "Interesting," she says. "You met a tool in week 3 that removes spaces from the ends of a string. It removes newlines too."
Rocket adds .strip() and the spacing snaps into place.
open("crew.txt") with no mode opens the file for reading. That is the same as mode "r". Inside the with block, f.read() gives the whole file as one string.
# read_all.py
with open("crew.txt") as f:
text = f.read()
print(text)
print(len(text), "characters") Rocket Raven Nova 18 characters
A for loop over the file gives one line at a time. Each line still ends with its newline, so use .strip() to remove it.
# greet_crew.py
with open("crew.txt") as f:
for line in f:
name = line.strip()
print("Welcome aboard,", name) Welcome aboard, Rocket Welcome aboard, Raven Welcome aboard, Nova
Opening a file that does not exist, for reading, gives a FileNotFoundError. Check the spelling of the name, and check that the file is in the same folder.
# missing.py
with open("crew_list.txt") as f:
print(f.read()) Traceback (most recent call last):
File "missing.py", line 2, in <module>
with open("crew_list.txt") as f:
~~~~^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'crew_list.txt' Now your programs can write and read. Tomorrow you will add to a file without wiping out what is already there.