简体   繁体   中英

How do I check user input from a file in Python?

Let's say I have a text file:

Alice,Bob,Charles,David,Emily,Frank

I want to check if a string that the user enters matches a name in the text file, something like this:

Name = str(input("Enter a name here: ")

if Name == Alice:
    print("Foo")
elif Name == Bob:
    print("Bar")

How do I do it?

  1. Assuming that you want to check if a string that the user enters matches a name in the text file then you should read your text file in advance and then compare to the user input as follows

    names = [i.split(',') for i in open('names.txt', 'r')][0] Name = input() [name+' is in the list' for name in names if name == Name]
  2. Assuming that you want to check if a string that the user enters matches a name in the name of a text file then you should read your text file names in advance and then compare to the user input as follows:

     names = os.listdir(directory) Name = input() [name+' is in the list' for name in names if name == Name]

lets assume that your directory looks something like this :

$cd folder
$ls 
Alice  Bob  Charles  David  Emily  Frank

Then you can do it by.

Name = str(input("Enter a name here: ")
if Name in os.listdir('folder'):
    print("Name found!!!!  {}".format(Name))

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