2012-08-15 115 views
0

到目前爲止,我有這個程序做我想做的。但是,在運行時,它將覆蓋最後一條員工記錄,而不是僅僅添加到文件中。我是新來的,並且一直盯着這幾個小時,但我還沒弄明白。只需要在正確的方向稍微推動一下。文本文件覆蓋寫入,不附加

# 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") 

回答

1

根據傳遞給打開的控制字符串,您每次打開要重寫的文件。將open ('EmployeeRecords.txt, 'w')更改爲open ('EmployeeRecords.txt', 'a+')。記錄將被追加到文件的末尾。

+0

完美的作品謝謝你。 – NineTail 2012-08-16 13:23:48

1

追加模式應該工作。

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

http://stackoverflow.com/questions/4706499/how-do-you-append-to-file-in-python – Kickaha 2012-08-15 21:15:30