我的尝试都没有成功,我尝试更改行,更改文本文件行。我在这里所做的是尝试搜索名称,该用户将其放入input(“ Whats your name?”)中,如果系统在文本文件中找到该名称,则会打印一条消息。 代码和CMD的屏幕截图。
# Atidarom text'ini faila, kuriam visi ban nickai
Banlistas = open('Listas_BAN.txt', mode='r').readlines()
name = input("~ Please enter Your name below\n")
clear()
# Checking if there's name in the BANLIST Which is currently in Listas_BAN
if name in Banlistas:
print('your name {n} is in the list'.format(n=name))
else:
print('your name {n}, was not found in the list'.format(n=name))
系统找不到名称,但是在文本文件中。 enter image description here enter image description here
P.S-对不起,我的英语,我也是python的新手
答案 0 :(得分:1)
name = input("~ Please enter Your name below\n")
ban_path = 'Listas_BAN.txt' # be sure to replace by the full path
with open(ban_path , mode='r', encoding='utf-8') as f:
if name in f.read():
print('your name {n} is in the list'.format(n=name))
else:
print('your name {n}, was not found in the list'.format(n=name))
这里有几件事:
with
关键字打开文件:它将负责文件的打开/关闭f.read()
将返回文件的全部内容,而无需遍历行