程序重写保存的文件数据

时间:2017-12-07 23:16:27

标签: python python-2.7

所以我有这个我用Python 2.7编写的程序,它接受用户输入的各种员工信息并将其写入文件。我将主要的代码块放入一个函数中,因为我希望能够多次运行它。我目前的代码如下:

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()

每当它运行时,它只保存文件中运行的函数,因此文本文件中只有9个数据,而只有3个,这是我输入程序的最后3个。我无法弄清楚为什么每次函数运行时都会覆盖数据,有人知道这段代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

您的问题是您正在使用openfile的'w'模式。 就像您可以在模式'r'中打开来阅读文件一样,您可以使用'a'附加到文件。

只需更改此行:

with open('employeeFile.txt', 'w') as dataFile:

with open('employeeFile.txt', 'a') as dataFile:

应该可以解决你的问题!