打开文件以追加错误

时间:2016-05-02 10:31:12

标签: python file append

我正在尝试打开一个文件进行追加,但是我一直得到我的try / except块的“except”部分,这意味着代码有一些错误,但我似乎无法找到确切的内容是错的。只有在我尝试打开这样的新文件时才会发生这种情况:

    results = open("results.txt", "a")
    results.append(score3)

这是我的完整代码:

import statistics

# input
filename = input("Enter a class to grade: ")

try:
    # open file name
    open(filename+".txt", "r")
    print("Succesfully opened", filename,".txt", sep='')
    print("**** ANALYZING ****")
    with open(filename+".txt", 'r') as f:
        counter1 = 0
        counter2 = 0
        right = 0
        answerkey = "B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
        a = []
        # validating files
        for line in f:
            if len(line.split(',')) !=26:
                print("Invalid line of data: does not contain exactly 26 values:")
                print(line)
                counter2 += 1
                counter1 -= 1
            if line.split(",")[0][1:9].isdigit() != True:
                print("Invalid line of data: wrong N#:")
                print(line)
                counter2 += 1
                counter1 -= 1
            if len(line.split(",")[0]) != 9:
                print("Invalid line of data: wrong N#:")
                print(line)
                counter2 += 1
                counter1 -= 1
            counter1 += 1
        #grading students
            score = len(([x for x in zip(answerkey.split(","), line.split(",")[1:]) if x[0] != x[1]]))
            score1 = 26 - score
            score2 = score1 / 26
            score3 = score2 * 100
            a.append(score3)
            # results file 
            results = open("results.txt", "a")
            results.write(score3)
        # in case of no errors
        if counter2 == 0:
            print("No errors found!")
        # calculating 
        number = len(a)
        sum1 = sum(a)
        max1 = max(a)
        min1 = min(a)
        range1 = max1 - min1
        av = sum1/number

        # turn to int
        av1 = int(av)
        max2 = int(max1)
        min2 = int(min1)
        range2 = int(range1)

        # median
        sort1 = sorted(a)
        number2 = number / 2
        number2i = int(number2)
        median = a[number2i]
        median1 = int(median)

        # mode
        from statistics import mode
        mode = mode(sort1)
        imode = int(mode)



    # printing
    print ("**** REPORT ****")
    print ("Total valid lines of data:", counter1)
    print ("Total invalid lines of data:", counter2)

    print ("Mean (average) score:", av1)
    print ("Highest score:", max2)
    print("Lowest score:", min2)
    print("Range of scores:", range2)
    print("Median Score:", median1)
    print("Mode score(s):", imode)


    results.close()


except:
    print("File cannot be found.")

1 个答案:

答案 0 :(得分:3)

我不认为有一种叫做追加写入文件的方法。您只能使用write或writelines方法进行写入。因为您已经使用追加权限打开了文件。它不会更改旧数据并将文本附加到文件中。

f=open('ccc.txt','a')
f.write('Hellloooo')
f.close()

希望它有所帮助。