Reputation:
I just need a little help with my code. I ask for name input and I try to make the code check if the input is in the user, but it always says that it's the user's first time.
name_file = open("NAME_DATA.txt", "r")
name = str(input("Hello, What is your first and last name?\n"))
if name in name_file:
Clear()
print("Good to see you again! It looks like you have used this before!")
tm.sleep(3)
name_file.close()
if name not in name_file:
Clear()
print("I see this is your first time using this software. Have fun! Just a disclaimer, your
name will be added to the name_data.txt file, but we will never share anyones name!")
tm.sleep(5)
name_file = open("NAME_DATA.txt", "a")
name_file.write(str(name) + "\n")
name_file.close()
Please somebody help me with this!!
Upvotes: 0
Views: 50
Reputation: 559
You should really consider using the with
context manager when working with files, this way you do not need to worry about opening and closing file handles. Additionally I would be surprised if you do not get an error on the conditional block name not in name_file
given you open the file with a different mode before closing it again. I would do something more like this
with open("NAME_DATA.txt", "r") as name_file:
data = name_file.read()
name = str(input("Hello, What is your first and last name?\n"))
if name in data:
Clear()
print("Good to see you again! It looks like you have used this before!")
tm.sleep(3)
else:
Clear()
print("I see this is your first time using this software. Have fun! Just a disclaimer, your
name will be added to the name_data.txt file, but we will never share anyones name!")
tm.sleep(5)
with open("NAME_DATA.txt", "a") as name_file:
name_file.write(str(name) + "\n")
Upvotes: 0
Reputation: 2607
As @Mike67 said in the comments before I could:
name_file = open("NAME_DATA.txt", "r").read()
Will read the file as text (string)
you can also use .readlines()
to make a list from each line in the txt files for further processing
Upvotes: 1
Reputation: 11342
You need to read the text file.
Try this code:
name_file = open("NAME_DATA.txt", "r")
data = name_file.read()
name = str(input("Hello, What is your first and last name?\n"))
if name in data:
Clear()
print("Good to see you again! It looks like you have used this before!")
tm.sleep(3)
name_file.close()
else: #if not name in data:
Clear()
print("I see this is your first time using this software. Have fun! Just a disclaimer, your
name will be added to the name_data.txt file, but we will never share anyones name!")
tm.sleep(5)
name_file = open("NAME_DATA.txt", "a")
name_file.write(str(name) + "\n")
name_file.close()
Upvotes: 2