if(x in y)不能在python文件I/O中工作

 云鹤 发布于 2023-02-13 13:53

我正在创建一个高分数据库,到目前为止有两件事情无效.

    如果我输入一个已存在于文件中的名称,它将忽略if语句(在代码中提到)我会对它在哪一行发表评论.

    当我输入名称和分数时,它将替换highscores.txt文件中的当前名称和分数.

这是我的档案:

name = str(input("Enter your name: "))
score = str(input("Enter your score: "))


file = open("N:\highscores.txt", "r")
if(name in file):
    print("You have already entered a score.")
    file.close()
else:
    file = open("N:\highscores.txt", "w")
    file.writelines(name + " : " + score + "\n")
    file.close()

此外,当我解决这个问题时,我如何按大小顺序订购它们?例如:1.450 2. 300等

谢谢.

1 个回答
  • Python文件对象不支持in成员资格测试,不.

    将文件读入字典,然后对其进行测试:

    with open("N:\highscores.txt", "r") as scoresfile:
        scores = {name.strip(): score.strip() for line in scoresfile if ':' in line for name, score in (line.split(':'),)}
    
    if name in scores:
        print("You have already entered a score.")
    else:
        with open("N:\highscores.txt", "a") as scoresfile:
            file.write('{} : {}\n'.format(name, score))
    

    请注意,您需要以附加模式打开文件以添加行; w将首先清除打开的文件.

    2023-02-13 13:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有