[英]Python Getting string from text file, and checking if there's matched word in the text file
我的嘗試都沒有成功,我嘗試更改行數,更改文本文件行。 我在這里所做的是嘗試搜索名稱,該用戶將其放入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))
系統找不到名稱,但是在文本文件中。 在此處 輸入圖像描述在 此處 輸入圖像描述
PS-對不起,我的英語,我也是python的新手
編輯: 在此處輸入圖片描述
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()
將返回文件的全部內容,而無需遍歷各行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.