2015-12-20 107 views
-1

我试图将学生的分数保存在文本文件中,但我被要求保存学生的最后三个分数。这听起来相当直接,但尝试各种不同的事情后,我仍然无法做到这一点。我一直在尝试使用他们的名字作为变化的变量,即如果他们的名字被输入多次。如何限制在文本文件中包含特定输入

这里是我可怜的最好的尝试 请帮助

class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number") 

    filename = (str(class_number) + "txt") 
    if any(name in s for s in filename): 
     for score in range (0,3): 
      with open(filename, 'a') as f: 
       f.write("\n" + str(name) + " also scored " + str(score) + " on difficulty level " + str(level_of_difficulty) + "\n") 
      with open(filename) as f: 
       lines = [line for line in f if line.strip()] 
       lines.sort() 
      name[-3] 
    else: 
     with open(filename, 'a') as f: 
      f.write("\n" + str(name) + " scored " + str(score) + " on difficulty level " + str(level_of_difficulty) + "\n") 
     with open(filename) as f: 
      lines = [line for line in f if line.strip()] 
      lines.sort() 
+0

我添加了一些代码,您可以查看。 – 7stud

回答

-1
filename = (str(class_number) + "txt") 

class_number已经是一个字符串 - 因为任何一个用户输入一个字符串。所以,让我们说,用户输入 “1”,那么你得到:

filename = "1txt" 

然后你做:

any(name in s for s in filename): 

当您遍历字符串 “1txt”:

for s in filename 

你收到信件,所以你问:

any(name in "1" ....) 

似乎是无意义的...

我被要求保存学生的最后三个分数。

根据你的代码,我不知道甚至是远程的意思。你怎么样发布:

  1. 我有这样的....

  2. 我想这个....

在此期间,这里的一些东西,你可以试试。 shelve模块将让您的生活更轻松:

import shelve 

fname = "scores" 

name = "John" 
current_scores = [75, 98] 

#shelve will add a .db extension to the filename, 
#but you use the name without the .db extension. 
with shelve.open(fname) as db: 
    old_scores = db.get(name, []) #db is dictionary-like. Get previously stored scores--if any, 
            # or return an empty list 
    old_scores.extend(current_scores) #Add the current scores to the old scores. 
    db[name] = old_scores[-3:] #Save the last three scores in the file. 


#Time passes.... 

nane = "John" 
current_scores = [67, 80, 41] 

with shelve.open(fname) as db: 
    old_scores = db.get(name, []) 
    old_scores.extend(current_scores) 
    old_scores.sort() 
    print(old_scores) 
    db[name] = old_scores[-3:] 


with shelve.open(fname) as db: 
    print(db["John"]) 

--output:-- 
[41, 67, 75, 80, 98, 98] 
[80, 98, 98] 
+0

它不起作用,它出现在线上的错误: – Ibrahim

相关问题