I am following the 'python crash course', one of the practice questions ask me to open/create the txt file 'guest_book' in append mode and create a while loop to ask user input their name, at the same time append their name into the 'guest_book' txt and print that they have been logged. I have wrote the following code.
filename = 'guest_book'
with open(filename, 'a') as f:
while True:
name = input('enter name ')
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")
The problem: the while loop is successful and the final print is also successful, however when I check the guest_book txt. it does not record the inputted name. Interestingly, by simply switching the order of while loop and open txt command, it seems to work, like this:
filename = 'guest_book.txt'
while True:
with open(filename, 'a') as f:
name = input('enter name ')
f.write(name + '\n')
print(f"You have been added to the guest book, {name}")
the only difference between the two codes are switched order of the while loop and "with open" line. Can someone explain to me why this order matters? No matter how hard I tried, I can't seem to understand the logic behind this. Thanks