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?
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]
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.