Reputation: 3
How can I check if the input already exists in the text file?
def Database():
file=open("Database.txt","a")
print("Welcome to Database")
name=input("Enter your name\n")
username=input("Enter your username\n")
password=input("Enter your password\n")
date=input("Enter the date\n")
while True:
if username in file():
print("Already exists")
username=input("Enter your username\n")
else:
file.write(name)
file.write("\n")
file.write(username)
file.write("\n")
file.write(password)
file.write("\n")
file.write(date)
file.write("\n")
file.close()
Database()
Upvotes: 0
Views: 3731
Reputation: 600
Since you are going to check several times, it is better to save the entire list in a csv file in a single line. This will reduce the read time.
Then simply check if username in csv file or not.
Add the following snippet and change according to the requirement.
import csv
alreadyIn=[]
with open('data.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
alreadyIn.append(row[0])
with open('data.csv', 'w+') as csvfile:
writer = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow([alreadyIn])
with open('data.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
allData = row[0]
if newInput in allData:
#your operations
Upvotes: 1
Reputation: 77860
Since you need to search the file several times, until the customer enters a new username, I recommend that you break this into steps:
Does that get you moving?
Upvotes: 1