Exercise 10-5 'Guest Book', E.Matthes: Pyhton Crash Course, 2nd ed

Hi!

I was trying to solve exercise 10-5 in the book:

Write a while loop that prompts users for their name. Collect all the names that are entered, and then write these names to a file called guest_book.txt. Make sure each entry appears on a new line in the file.

It took me a while and at some point I checked for the solution given by the author

from pathlib import Path

path = Path('guest_book.txt')

prompt = "\nHi, what's your name? "
prompt += "\nEnter 'quit' if you're the last guest. "

guest_names = []
while True:
    name = input(prompt)
    if name == 'quit':
        break

    print(f"Thanks {name}, we'll add you to the guest book.")
    guest_names.append(name)

# Build a string where "\n" is added after each name.
file_string = ''
for name in guest_names:
    file_string += f"{name}\n"

path.write_text(file_string)

It’s difficult for me to understand what is the part of ‘file_string’ in all this and is there any way to write this program without it?
Or I’m curious if there could be any other more simplifed solutions to the code?

Thank you for your ideas

file_string is used here to collect all the text before writing it out to the file. That is not really necessary, you can write each piece of data separately to the file as well. That would be my preferred approach actually. Like this:

with open(path, "wt") as fp:
    for name in guest_names:
        fp.write(f"{name}\n")

If you do want to combine the list of strings into a single string separated by newlines, you can also do "\n".join(guest_names).

Thanks! I really did not know, these kind of statements like ‘.join’ even exist :o

“\n”.join(guest_names) is not exactly equivalent to file_string as it probably won’t end in “\n”.

That may or may not matter to the teacher :slight_smile: