0

到目前为止,我有这个程序做我想做的事。但是,在运行时,它将覆盖最后一个员工记录,而不仅仅是添加到文件中。我是 prgramming 的新手,已经盯着这个看了好几个小时了,但我还是看不懂。只需要在正确的方向上轻轻一点。

# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
    fullName = fullName
    age = age
    salary = salary
def displayEmployee():
    print("\n")
    print("Name: " + fullName)
    print("Age: " + age)
    print("Salary: " + salary)
    print("\n")

EmployeeArray = []

Continue = True
print ("Employee Information V2.0")

while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")

choice = input("Pick an option: ")

if choice == "1":
    fullName = input ("Enter Full Name: ")
    if fullName == "":
        blankName = input ("Please enter a name or quit: ")
        if blankName == "quit":
            print ("Goodbye!")
            print ("Hope to see you again.")
            Continue = False
            break
    age = input ("Enter Age: ")
    salary = input ("Enter Salary: ")
    EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
    EmployeeRecords.write("Full Name: " + fullName + '\n')
    EmployeeRecords.write("Age: " + age + '\n')
    EmployeeRecords.write("Salary: " + salary + '\n')
    EmployeeRecords.close()
elif choice == "2":
    EmployeeRecords = open ('EmployeeRecords.txt', 'r')
    data = EmployeeRecords.read()
    print ("\n")
    print (data)
    EmployeeRecords.close
elif choice == "3":
    answer = input ("Are you sure you want to quit? " "yes/no: ")
    if answer == "yes" or "y":
        print ("Bye!")
        Continue = False
    else:
        Continue
else:
    print ("Please choose a valid option")
    print ("\n")
4

2 回答 2

1

附加模式应该可以工作。

EmployeeRecords = open('EmployeeRecords.txt', 'a')
于 2012-08-15T21:14:47.610 回答
1

根据传递给 open 的控制字符串,您每次都打开要重写的文件。更改open ('EmployeeRecords.txt, 'w')open ('EmployeeRecords.txt', 'a+')。并且记录将附加到文件的末尾。

于 2012-08-15T21:16:48.830 回答