I'm trying to save all of the inputs entered by the user in a text file using Python. I want to make sure all of the inputs that are entered stored in the file until I fully exit out of the program, in this case until I press "enter" to stop the list. I also need to check the input names and see if it matches any of the previous entry.
The problem with my program right now is that the text file updates the latest names entered when I exit out of the code. I need my program to save all of those names in a list UNTIL the program is over because I have to make that there are no duplicates. I will have to warn the user that the name already exists, which I also need help on. I made a separate function for creating and writing text files from my inputs on my code below, but I also noticed I can implement it in the get_people() function. I'm not sure what the best strategy is to either create a new function for it or not. There is definitely something wrong with writing files.
The text file should have this format:
Taylor
Selena
Martha
Chris
Here is my code below:
def get_people():
print("List names or <enter> to exit")
while True:
try:
user_input = input("Name: ")
if len(user_input) > 25:
raise ValueError
elif user_input == '':
return None
else:
input_file = 'listofnames.txt'
with open(input_file, 'a') as file:
file.write(user_input + '\n')
return user_input
except ValueError:
print("ValueError! ")
# def name_in_file(user_input):
# input_file = 'listofnames.txt'
# with open(input_file, 'w') as file:
# file.write(user_input + '\n')
# return user_input
def main():
while True:
try:
user_input = get_people()
# name_in_file(user_input)
if user_input == None:
break
except ValueError:
print("ValueError! ")
main()
withto open the file, the file will be closed immediately after you write to it. That will flush the data to the file, you don't have to wait until the program exits.