4

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()
3
  • I don't understand the question. Since you use with to 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. Commented Feb 28, 2019 at 4:12
  • @Barmar I fixed the 'with' line. My problem now is updating that file whenever the user enters a name because I need to make sure warn the user if they have listed the name before. I'm trying to avoid duplicate inputs. Commented Feb 28, 2019 at 4:42
  • You probably want to store the input while the input loop is running and only then write the file. Or is there any reason every name is immediately written to the file once it passes validation? Commented Feb 28, 2019 at 7:28

2 Answers 2

1

The problem is the way the code opens the file:

with open(input_file, 'w') as file:

Checking the manual - https://docs.python.org/3.7/library/functions.html?highlight=open#open the code is overwriting the file every open() because of the "w". It needs to open it for appending "a":

with open(input_file, 'a') as file:

Appending will create the file if it does not exist, or append to the end of any existing file of the same name.

EDIT: To check if you have seen the name already, pass a list of "already seen" names to the get_people() function, and append any new name to that list too.

def get_people( already_used ):
    print("List names or <enter> to exit")
    while True:
        try:
            user_input = input("Name: ")
            lower_name = user_input.strip().lower()
            if len(user_input) > 25:
                raise ValueError
            elif lower_name in already_used:
                print("That Name has been used already")
            elif user_input == '':
                return None
            else:
                already_used.append( lower_name )
                input_file = 'listofnames.txt'
                with open(input_file, 'a') as file:
                    file.write(user_input + '\n')
                return user_input

        except ValueError:
            print("ValueError! ")

def main():
    already_used = []
    while True:
        try:
            user_input = get_people( already_used )
            # name_in_file(user_input)
            if user_input == None:
                break

        except ValueError:
            print("ValueError! ")

main()
Sign up to request clarification or add additional context in comments.

4 Comments

What does this have to do with the question?
@Barmar - Every iteration of the loop in get_people() loop is overwriting the existing file, thus only leaving the last name entered, which matches the OP's problem description.
The question confused me, I thought his problem was that nothing was being written to the file until he exited the program. I thought it had to do with flushing, until I checked the code more closely.
@Kingsley the 'a' works, but it doesn't update the txt whenever it is entered until I fully exit the program. I have to check to make sure there are no duplicates of the names.
0

If I understood your question correctly, I'd say. You can read the file and put all lines into a list and then you can check whether input already exist or not. here I edited your code a bit.

def get_people(name_list):
    print("List names or <enter> to exit")

    while True:
        try:
            user_input = input("Name: ")
            write_line = user_input + '\n'

            if write_line in name_list:
                print('already exist..!')
                raise ValueError
            name_list.append(write_line)

            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(write_line)
                return user_input

        except ValueError:
            print("ValueError! ")


def main():

    name_list = []
    f = open("listofnames.txt")
    name_list = f.readlines()

    while True:
        try:
            user_input = get_people(name_list)
            # name_in_file(user_input)
            if user_input == None:
                break

        except ValueError:
            print("ValueError! ")

main()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.