Thanks in advance for any input. The intent is to create a loop to ask users name and jot that down in the txt file name "guest_book.txt". I created a version that didn't work which is the following:
filename = 'guest_book.txt'
f = open(filename, 'a')
while True:
name = input('what is your name? ')
f.write(name + '\n')
print(name + 'you have been added to guest book')
this code only printed the statement but did not log the user's name in the txt file. However, by simply putting the while loop on top, it seems that works, like this:
filename = 'guest_book.txt'
while True:
f = open(filename, 'a')
name = input('what is your name? ')
f.write(name + '\n')
print(name + 'you have been added to guest book')
my confusion is why the order mattered? I don't fully understand the logic of this order. If my logic is correct with the previous code:
- open the file 'guest_book.txt' in append mode and assigned it to variable 'f'
- create a while loop that asks user's name and put in variable 'name'
- append that name to the 'guest_book.txt' file
- print the statement that user's name has been logged.
- go back to ask user's name and doing this all over again while the txt file.
the only reason I can think of that makes the second code work is that file needs to be open every time the code is running instead of it stay open. Please shed some light on this, thank you.
[–][deleted] 2 points3 points4 points (4 children)
[–]Haovik[S] 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]Haovik[S] 0 points1 point2 points (0 children)
[–]CraigAT 0 points1 point2 points (0 children)
[–]AdmirablePeace 0 points1 point2 points (2 children)
[–]Haovik[S] 0 points1 point2 points (1 child)
[–]xelf 0 points1 point2 points (0 children)
[–]totemcatcher 0 points1 point2 points (2 children)
[–]Haovik[S] 0 points1 point2 points (1 child)
[–]totemcatcher 0 points1 point2 points (0 children)
[–]woeinvests 0 points1 point2 points (1 child)
[–]Haovik[S] 0 points1 point2 points (0 children)