tojas
tojas

Reputation: 3

how to check if user input already exists in a text file python

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

Answers (2)

user5722540
user5722540

Reputation: 600

  1. Read the file from start to end and save it in a list.
  2. 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.

  3. 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

Prune
Prune

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:

  1. Read the file into a data structure you find convenient, some sort of table of usernames. Close the file.
  2. When the customer enters a name, you use the in operator to check the list of existing names.
  3. Once you get the new information, open the file again for "append", and add the new information to the file.

Does that get you moving?

Upvotes: 1

Related Questions