Reputation: 57
So I have this program that I've written in Python 2.7 which takes user input of various employee information and writes it to a file. I put the main block of code into a function, because I want to be able to run it multiple times. The code I currently have is below:
def employeeInformation():
# opens text file data will be stored in
with open('employeeFile.txt', 'w') as dataFile:
# gets user input for employee name
employeeName = raw_input('Employee Name: ')
# checks if the input is a string or not
if not employeeName.isalpha():
print('Invalid data entry')
else:
# if input is string, write data to file
dataFile.write(employeeName + '\n')
# gets user input for employee age
employeeAge = raw_input('Employee Age: ')
if not employeeAge.isdigit():
print('Invalid data entry')
else:
# if input is number, write data to file
dataFile.write(employeeAge + '\n')
# gets user input for employee role
employeeRole = raw_input('Employee Role: ')
if not employeeRole.isalpha():
print('Invalid data entry')
else:
# if input is string, write data to file
dataFile.write(employeeRole + '\n')
employeeSalary = raw_input('Employee Salary: ')
if not employeeSalary.isdigit():
print('Invalid data entry')
else:
# if input is number, write data to file
dataFile.write(employeeSalary + '\n')
dataFile.close()
employeeInformation()
employeeInformation()
employeeInformation()
Whenever it runs however, it only saves on of the function runs in the file, so instead of there being 9 pieces of data in the text file, there are only 3, which are the last 3 I input into the program. I can't figure out why it seems to be overwriting the data each time the function runs, does anyone know whats wrong with this code?
Upvotes: 1
Views: 60
Reputation: 426
your problem is you are using the 'w'
mode of an openfile.
just as you can open in mode 'r'
for reading a file, you can use 'a'
for appending to a file.
just change this line:
with open('employeeFile.txt', 'w') as dataFile:
to
with open('employeeFile.txt', 'a') as dataFile:
that should solve your problems!
Upvotes: 2