创建新文件的问题

时间:2016-05-02 18:55:54

标签: python file

我试图在程序结束时创建一个新文件以附加信息,但是文件由于某种原因没有被创建(我的代码中要查看的位置是#曲线区域)。我最好的猜测是变量" filename"在程序开始时建立,不会一直向下到我建立新文件名的位置。我的代码如下:

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)
            sscore3 = str(score3)

            # results file
            results = open(filename+"_grades.txt", "a")
            results.write(line.split(",")[0])
            results.write(",")
            results.write(sscore3[:2])
            results.write("\n")
            results.close()
        # 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)
    # curve
    part = input("Would you like to apply a curve to the scores? (y)es or (n)o?")
    if part == "y":
        newmean = input("Enter desired mean score:")
        part1 = newmean - av1
        part2 = sscore3 + part1
        results = open(filename+"_grades_with_curve.txt", "a")
        results.write(line.split(",")[0])
        results.write(",")
        results.write(sscore3[:2])
        results.write(",")
        results.write(part2)
        results.write("\n")
        results.close()





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

当我输入" y"它会跳到except块。最后尝试创建新列表,这意味着问题在于创建这个新列表。

1 个答案:

答案 0 :(得分:3)

代码太长,需要重新组织。

您的代码可能存在其他问题,并且您正在尝试修复错误的代码。

几点提示:

如果不将文件对象分配给变量

,请不要打开文件
open(filename+".txt", "r")

您打开文件,没有机会关闭它,因为您忽略了返回的文件 文件对象。

使用with块打开/关闭文件

with open(input_fname, 'r'):
    # work with the file

到处学习。

不要重新打开文件以写入结果

您的代码重复打开结果文件(以“a”模式)。你最好只打开一次。

您甚至可以在一个上下文块中打开多个文件:

with open(input_fname, 'r') as f, open(output_fname, "a") as results:
    # work with the files

重复使用一次计算结果

在很多地方你分开了一行:line.split(",")

您应将结果放入变量并重复使用。

rec = line.split(",")

永远不要忽视异常! (最严重的问题)

最后一个块是捕捉所有异常而不给你任何迹象,出了什么问题(甚至是 更糟糕的是,它告诉你可能没有找到文件的错误信息。)

所以而不是:

try:
    # some code
except:
    print("File not found.")

至少要重新启动异常以便从中学习:

try:
    # some code
except:
    print("File not found.")  # this is probably to be removed as misleading message
    raise

实际上,您可以完全忽略完整的顶级尝试 - 除了块并让异常显示 告诉你出了什么问题。

将代码拆分为更小的块。

将代码拆分为较小的函数应简化调试和使用