【问题标题】:How do you limit the inclusion of a specific input in a text file您如何限制在文本文件中包含特定输入
【发布时间】:2016-03-26 19:10:21
【问题描述】:

我试图将学生的分数保存在文本文件中,但是我被要求保存学生的最后三个分数。这听起来很简单,但是在尝试了各种不同的事情之后,我仍然做不到。我一直在尝试使用他们的名字作为改变的变量,即如果他们的名字被多次输入。

这是我可怜的最佳尝试 请帮忙

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()

【问题讨论】:

  • 我添加了一些代码,您可以查看。

标签: python list random slice


【解决方案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]

【讨论】:

  • 它不起作用它出现了一个错误就行了:
猜你喜欢
  • 2016-07-27
  • 2023-03-30
  • 1970-01-01
  • 2018-01-14
  • 2017-03-31
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多