Python程序没有写入文件

时间:2015-01-14 21:09:01

标签: python file-handling

我正在创建一个测验程序,我希望能够将用户得分保存到文本文件中。但是我应该写入文本文件的代码不是;文本文件似乎没有动过。没有遇到任何错误。

with open("Class {0} data.txt".format(classNo),"r") as src:

        # list containing all data from file, one line is one item in list
        data = src.readlines()

        for ind,line in enumerate(data):

            if surname.lower() and firstName.lower() in line.lower():
                # overwrite the relevant item in data with the updated score
                data[ind] = "{0} {1}\n".format(line.rstrip(),score)
                rewrite = True

            else:
                with open("Class {0} data.txt".format(classNo),"a") as src: 
                    src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))

    if rewrite == True:
        # reopen src in write mode and overwrite all the records with the items in data
        with open("Class {} data.txt".format(classNo),"w") as src: 
            src.writelines(data)
    flag = False

0 个答案:

没有答案