Python3 Search For Input In Txt File
Basically what I want to achieve is this. I have a text file with only the word test in it. When the script is run it pops up with an input and the user would write test. That inpu
Solution 1:
line.strip()
is not in-place; it returns the stripped line. Try line = line.strip()
.
Unrelated advice: use a context manager to open / close the file:
withopen("rtf.txt") as file:
for line in file:
...
# No need to call `file.close()`, it closes automatically here
This works as expected for me:
find_name.py:
name = input("What's your name? ")
withopen("names.txt") as file:
for line in file:
if line.strip().startswith(name):
print("Found name!")
breakelse:
print("Didn't find name!")
names.txt:
foo
bar
baz
$ python3 find_name.py
What's your name? bar
Didn't find name!
Found name!
Solution 2:
discordname = input("What's your discord name? ")
withopen('rtf.txt') as file:
contents = file.readlines()
if discordname in contents:
print("It exits")
else:
print("Doesnot exits")
Just try this. it works. Or if you want to check on every word try read() instead of readlines()
Post a Comment for "Python3 Search For Input In Txt File"