python - 读取文件并检查数据是否在文件中。 Python

标签 python python-3.x

我正在为一个学校项目制作一个骰子游戏。当你开始游戏时,你输入你的名字,它需要从文件“Player_Names.txt”中读取之前玩过的玩家的名字列表,如果这个名字不在列表中,那么他们会得到一个“欢迎”,但是如果他们得到“欢迎回来”吗?

在我当前的代码中,它只读取文件中的第一行,因此如果名称不在第一行,它会返回一条欢迎新玩家的消息。 另外,如果它是名字的一部分,那么如果您先输入“Matthew”,然后再输入“Matt”,它会给您一条“欢迎回来”的消息,但“Matt”是另一个人,所以它应该是一条“欢迎”消息. 此外,如果您输入的名称在列表中,但在文件的第 2 行,您什么也得不到,程序将继续执行下一行代码。

Names = open("Player_Names.txt", "r+")  
player1 = input("Enter your name: ")  
if player1 in Names.readline():  
    print("Welcome back you are player 1")  
elif player1 not in Names.readline():  
    print("Welcome you are player 1")  
    Names.write(player1)  
    Names.write("\n")  

如何让程序读取所有行并将输入的单词视为整个单词而不是像“Matthew”示例中的字母?

最佳答案

这里有几个问题:

if player1 in Names.readline():  
    print("Welcome back you are player 1")  
elif player1 not in Names.readline():  

这个结构通常是多余的,因为第一个条件是第二个条件的否定,所以你可以这样写:

if player1 in Names.readline():  
    print("Welcome back you are player 1")  
else:

但在那种情况下,Names.readline() 具有消耗第一行的副作用。所以它们不等价。

此外,如果您的文件中有几行,您的算法将不起作用。

我会用这些行创建一个 list 并使用 any:

lines = Names.readlines()
if any(player1 in line for line in lines):
   # known player
else:
   # new player

请注意,您可以使用 set 和精确匹配创建更高效​​的查找:

lines = {x.strip() for x in Names}
player1 = player1.strip()
if player1 in lines:
   ....
else:

关于python - 读取文件并检查数据是否在文件中。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54447051/

相关文章:

python - 什么控制 Tkinter 中的自动窗口大小调整?

python - 如何在 Hive 中将一列拆分为两列

python-3.x - 为什么我会收到错误 ModuleNotFoundError : No module named 'azure.storage' during execution of my azure python function?

python - 打印()到上一行?

python-3.x - 更改 Pandas 中的栏项目名称

Python包安装问题

python - SQLAlchemy - 过滤子查询负载

python - Linux 新手 : need some help installing wxpython development environment on ubuntu 18. 04

用于可索引字符串列表的 Python 数据结构

python - 来自 itertools 食谱的成对总是给出与 zip(a, a[1 :])?