【发布时间】:2016-08-27 02:11:47
【问题描述】:
我正在尝试打开一个文件进行附加,但我不断收到我的 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.")
【问题讨论】:
-
你能用try/except块分享完整的代码吗...
-
试试
results.write(score3) -
你应该总是尽量避免除了所有的块,因为它们吃错误。只捕获您期望发生的异常/错误。
-
尝试在 results.write() 行之后保留 results.close() 函数。因为它在循环中循环,并且每次尝试打开已被其他进程打开的文件时。 :-)
-
results.write(score3)不起作用,因为您需要将字符串写入文件,而不是数字。该调用引发TypeError,但您未命名的except捕获该错误并打印出误导性的“找不到文件”。消息。