2015-04-23 72 views
0

这是遇到我到目前为止的代码错误使用“.format”

def Save_Scores(): 
    global score 
    score=str(score) 
    file=open("Class{}.txt",'a').format(group) 
    file.write("\n") 
    file.write ("Name: "+name+"\n") 
    file.write("Score: "+score+"/10\n") 
    file.close() 
quiz() 

但是我遇到这个错误时,函数跑

line 42, in Save_Scores 
file=open("Class{}.txt",'a').format(group) 
AttributeError: '_io.TextIOWrapper' object has no attribute 'format' 
+1

您是不是要找“ ”类{} TXT。“ .format(集团)'? – bereal

回答

3

str.format()是对String对象的方法,但您正试图在文件上调用它。它应用到你想传递给open()呼叫字符串:

file = open("Class{}.txt".format(group), 'a') 

其他最佳实践可以应用在这里:

  • 而不是使用score作为一个全球性,使其成为一个参数传递给你的函数,然后在调用函数时将其传入。

  • 您还使用namegroup作为全局变量,这些也应该是这里的参数。使用with声明让Python为您关闭文件。

  • 您也可以对写入文件的数据使用字符串格式,而不是使用连接。

这些变化的功能应该是这样的:

def Save_Scores(group, name, score): 
    with open("Class{}.txt".format(group), 'a') as file: 
     file.write("\nName: {}\nScore: {}/10\n".format(name, score)) 
相关问题