文字文件覆盖而非附加

时间:2012-08-15 21:09:39

标签: loops io python-2.7

到目前为止,我有这个程序做我想要的。但是,当它运行时,它将覆盖最后一个员工记录,而不是仅添加到文件中。我刚接触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")

2 个答案:

答案 0 :(得分:1)

追加模式应该有效。

EmployeeRecords = open('EmployeeRecords.txt', 'a')

答案 1 :(得分:1)

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