File needs to save three names, it is only saving the last input

Question:

Here is the code:

import os

def createFile():
    employee = open("namesEmployees.txt","a")
    print("The file has been created")
    employee.close()

def addInfo():
    for i in range(3):
        data = input("Type the name of the employee: ")
    employee = open("namesEmployees.txt","w")
    for i in range(3):
        employee.write (data + "n")
    print("The names have been added")
    employee.close()

def displayInfo():
    employee = open("namesEmployees.txt","r")
    name = employee.read()
    print(name)
    employee.close()


createFile()
addInfo()
displayInfo()

When I try to run the code, if I input three different names and then display it, the display only shows the last name three times. What can I do so it saves the three different names properly?

Asked By: Andrea

||

Answers:

Rewrite the addInfo() function as next:

def addInfo():
    employee = open("namesEmployees.txt","w")
    for i in range(3):
        data = input("Type the name of the employee: ") 
        employee.write (data + "n")
    print("The names have been added")
    employee.close()
Answered By: Aksen P

The createFile function is unnecessary because the file is (if possible) created in the addInfo function. You should not repeat things like filenames as literals in multiple functions. Using a constant is better (although ‘constant’ in Python is merely a convention). Use Context Manager for file handling. Allow for various values for the number of input values required (entries)

FILENAME = 'namesEmployees.txt'

def addInfo(entries=3):
    if entries > 0:
        with open(FILENAME, 'w') as output:
            for _ in range(entries):
                data = input('Type the name of the employee: ')
                print(data, file=output)
            print('The names have been added')

def displayInfo():
    with open(FILENAME, 'r') as data:
        print(data.read(), end='')

addInfo()
displayInfo()
Answered By: DarkKnight
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.