1

I'm starting my first project in Python(started two weeks ago).

This is something that I didn't learn on the course and it's not very clear on internet due to many different ways to do it. This is the bit of code I have written and I need the input to be saved in a text file, to have the list of names of the employees.

if name.lower() == "add":
        n_input = input("Name:")
        with open('names.txt', 'w') as f:
            f.write(n_input)

When I run this it works perfect, no traceback. But it's not saving the input in the list. I accept critiques, recommendations, changes, etc. As I said I'm new and I only want to learn.

Thank you very much.

FULL CODE BELOW:

snames = list()
f_n = (open('names.txt')).read()
#names_f = f_n.read()
print("Welcome to NAME.app")
while True:
    name = input("Please select waiter/tress name - ADD to save new name - LIST to see saved names:")
    #try:

    if name.lower() == "add":
        n_input = input("Name:")
        with open('names.txt', 'w') as f:
            f.write(n_input)
        continue

    elif name == snames:
        print(name)#doubtful line. print name of list.

    elif name.lower() == "list":
        print(f_n)

    elif name == "exit":
        exit()
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214

1 Answers1

1

When you write to a file, you replace everything in that file. If you want to add to the file, use with open('names.txt', 'a') as f to append the file.

How do you append to a file in Python?

I would make sure these were separated by a newline as well:

if name.lower() == "add":
        n_input = input("Name:")
        with open('names.txt', 'a') as f:
            f.write(n_input + "\n")

NOTE: This example will have an empty last line.

Ayush Garg
  • 2,234
  • 2
  • 12
  • 28
  • Thank you very much. That's working now it's adding the names. Any possibility of a way of updating the file info? When I write a name in the file and then I want to check the list in the file I have to exit the code to see the names added. Thank you anyway !! – Alejandro Trinchero Nov 24 '20 at 18:02
  • 1
    @AlejandroTrinchero You should create a new question for that. – Ayush Garg Nov 24 '20 at 18:03