- Press the Tab key one time to properly indent under the for loop. Now that you are
properly indented, type my_friend = input("Friend's name: ") and
press Enter. (You learned about getting keyboard input into a Python script in Hour 4,
“Understanding Python Basics.” Go back there to refresh your memory if needed.) - Press the Tab key one time to properly indent under the for loop. Now that you are
properly indented, type my_friend = my_friend + '\n' and press Enter.
Python will now add the needed newline escape sequence to the end of each friend’s
name. - Press the Tab key one time to maintain the proper indentation under the for loop.
Type my_friends_file.write(my_friend) and press Enter. This Python
statement causes the name to be written out to the friends.txt file. - Press the Enter key two times to kick off your loop for filling the friends.txt
file with data. - Each time the loop asks you for a friend’s name, enter a name from this list and then
press Enter:
Chris
Zack
Karl
Zoe
Simon
John
Anton
Don’t let it throw you that a number displays after each name you enter. Remember
that the .write method displays the number of characters it wrote to a file. (Have
you figured out who these people are yet?) - So that you can now read the file from the beginning, reset the file pointer to the start
of the file by typing my_friends_file.seek(0) and pressing Enter. - Create a for loop to read the newly populated friends file by typing for
my_friend in my_friends_file: and pressing Enter. Notice that there is
no need to close and reopen the file. This is because in step 5, the file was opened
with the mode w+, which allows you to write to the file and read it. - Press the Tab key one time and then type print (my_friend, end=' ').
This causes the data read into the Python script from the file to be displayed to your
screen. - Press the Enter key two times. You should see the friends’ names from the
friends.txt file displayed to the screen. - Close the friends.txt file by typing my_friends_file.close() and
pressing the Enter key. Now the file is properly closed. - Just to double-check, type my_friends_file.closed and press the Enter key.
If the file is truly closed, you should receive back the word True. If you get False,
singke
(singke)
#1