Danny Garcia
Danny Garcia

Reputation: 227

Issue with creating new file

I'm trying to make a new file at the end of a program to append info into, however the file isn't being created for some reason (the place in my code to look at is the #curve area). My best guess is that the variable "filename" established at the beginning of the program, isn't carrying all the way down to where I establish the new file name. My code is as follows:

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

and It skips to the except block when I enter "y" at the end to try and create the new list, meaning the issue is within creating this new list.

Upvotes: 0

Views: 51

Answers (1)

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44092

The code is too long and requires reorganization.

It is likely, there are other problems with your code and you are trying to fix wrong one.

Few hints:

Do not open file without assigning the file object to a variable

open(filename+".txt", "r")

You open the file and have no chance to close it as you ignore the returned file object.

Use with block to open/close your files

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

Learn doing so everywhere.

Do not reopen file for writing results

Your code repeatedly opens the result file (in "a" mode). You have better opening it only once.

You may even open multiple files within one context block:

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

Reuse once calculated result

In many places you split the line: line.split(",").

You shall put the result into variable and reuse it.

rec = line.split(",")

Never ignore exceptions!!! (most serious problem)

The final block is catching all exceptions without giving you any sign, what went wrong (or even worse, it tells you probably wrong information that the file was not found).

So instead of:

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

at least reraise the exception to learn from it:

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

In fact, you can completely ignore complete top level try - except block and let the exception show up telling you what went wrong.

Split your code into smaller chunks.

Having the code split to smaller functions shall simplify debugging and usage

Upvotes: 3

Related Questions