简体   繁体   中英

Python Getting string from text file, and checking if there's matched word in the text file

None of my tried attempts were succeed, i tried to change the lines, change the text file lines. What I'm doing here, is trying to search for the name, which user puts inside input("Whats your name?"), and if the system founds the name in the text file, it prints a message. Screenshot of the code, and 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))

The system is not finding the name, but it is in the text file. enter image description here enter image description here

PS - Sorry for my English, I'm also new to python

EDIT : enter image description here

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

A few things here:

  • you should use the with keyword to open your file: it will take care of the opening/closing of your file
  • adding the encoding could be helpful to manage special characters
  • f.read() will return the full content of the file, no need to iterate over the lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM