【问题标题】:Traceback error when handling text files处理文本文件时出现回溯错误
【发布时间】:2015-04-29 19:57:15
【问题描述】:

我创建了这段代码,它执行一个测验,然后根据用户输入(类)将结果写入一个文本文件。 所有文件处理代码对我来说似乎都是正确的,但是当我运行程序时,我会遇到“回溯(最近一次调用最后一次): Traceback (most recent call last):" 错误,然后程序崩溃了。

我只是在使用不同的代码时遇到了同样的问题并得到了答案,但我没有再犯我犯的错误(尝试一次将多个变量写入文件),因此该答案不适用这次。

import random 

forename="" 
surname=""
classno=0
numberone=0 
numbertwo=0
correct=False
score=0
ops = ["+", "x", "-"] 



while forename == "" or forename.isnumeric():
    forename=input("What is your first name? ")
    if forename == "": 
        print("You have to enter your first name.")
    if forename.isnumeric() == True:
        print("Your name must contain letters.")

while surname == "" or surname.isnumeric():
    surname=input("What is your surname? ")
    if surname == "":
        print("You have to enter your name.")
    if surname.isnumeric() == True:
        print("Your name must contain letters.")

while classno not in [1,2,3]: 
    while True:
        try:
            classno=int(input("What class are you in? "))
            break
        except ValueError:
            print("That wasn't right. Please try again.")



for x in range(10): 
    operation=random.choice(ops) 

if operation == "-": 
    numberone=random.randint(0,10) 
    numbertwo=random.randint(0,numberone)

elif operation == "x":
    numberone=random.randint(0,12)
    numbertwo=random.randint(0,12) 

else:
    numberone=random.randint(0,100)
    numbertwo=random.randint(0,(100-numberone))

while True:
        try:
            answer=int(input("What is " + str(numberone) + str(operation) + str(numbertwo) + "? "))
            break 
        except ValueError: 
            print("Incorrect input. Please try again.")


if operation=="+":
    if answer==numberone+numbertwo:
        correct=True

elif operation=="-":
    if answer==numberone-numbertwo:
        correct=True

else:
    if answer==numberone*numbertwo:
        correct=True

if correct==True:
    print("Correct!")
    score=score+1

else:
    print("Wrong!")

correct = False



info = str(forename) + "," + str(surname) + "," + str(score) + "\n"    



if classno == 1:
    file=open("class1.txt", "a")

elif classno == 2:
    file=open("class2.txt", "a")

else:
    file=open("class3.txt", "a")


maxnames = sum(1 for line in file)
name = [[] for i in range(maxnames)]   #creates empty list


for count in range(maxnames):
    line = file.readline()   #defines one line
    line=line.strip("\n")   #defines where lines end
    data = line.split(",")  #defines each data particle

    name[count].append(data[0])   #puts name in
    name[count].append(data[1])   #puts scores in
    name[count].append(data[2])
    name[count].append(data[3])


if forename == name[c][0] and surname == name[c][1]:
    name[c][4]=name[c][3]
    name[c][3]=name[c][2]
    name[c][2]=score
else:
    file.write(info)

file.close()


print("You scored",score,"out of 10.")

这是我所看到的:

【问题讨论】:

  • 你能发布完整的错误吗?
  • 追溯?什么 ?最近有哪个电话?
  • 这是完整的错误 - 我已经用截图编辑了我的帖子。 @bladexeon
  • 您确定编辑通过了吗?我没有看到任何截图,并且在帖子修订页面上只有原始版本。
  • 这就是@anmol_uppal的全部内容!我已经在原始帖子上发布了屏幕截图。

标签: python file-handling traceback


【解决方案1】:

问题始于您打开一个文件进行写入(通过使用'a' 模式)然后尝试从中读取。如果您将其更改为'r+',问题可能会自行解决。如果没有实际的回溯,就无法确定。

【讨论】:

  • 我试过这个,但它对我不起作用。我正在努力获得实际的回溯 - 我有点新手啊哈哈!
  • @gulliver 打开你的终端并输入python3 path/to/your/python/file.py
  • @gulliver 您需要使用python3 运行它,而不仅仅是python。您已经在 Python3 中编写了代码(input 调用的结果是一个字符串),通常系统 python 是 Python2(input 调用的结果是对 Python 对象的引用)
  • 我终于成功了,哈哈哈!对于那个很抱歉。我得到“回溯(最近一次通话最后一次):文件“./student.py”,第 108 行,在 name[count].append(data[1]) IndexError: list index out of range”。跨度>
  • @gulliver 无论你在哪一行都不包含逗号(它可能是空白的?)
猜你喜欢
  • 2022-06-15
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 2015-12-08
  • 1970-01-01
相关资源
最近更新 更多