Question
Python: 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
Python:
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
My problem with my program right now is that the text file only updates the latest name I inputted 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 sure if any of those names are repeated. I will have to warn the user that the name already exists. 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 Karlie
Here is my code below:
def get_people(): print("List names orto 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, 'w') as file: file.write(user_input + ' ') 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 + ' ') # 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()
Thank you so much!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started