how to match exact word in csv file? - python

I am a beginner coder here and I am trying to do a simple registration/login system using an external csv file.
my issue--> let's say I have an existing user "john" when my program promts for a name during registration and I enter the letter j or jo or joh
output --> user existed
how can I solve this issue?
import csv
name = input("register your name: ")
name=name.replace(" ", "")
with open("datafile.csv","r") as file:
content=file.read()
loop=True
while loop!=False:
if name in content :
name = input("name taken pls try again: ")
name=name.replace(" ", "")
else:
loop=False
password=input("new password: ")
with open("datafile.csv","a+",newline="") as file:
f=csv.writer(file)
f.writerow([name,password])
def main():
with open("datafile.csv","r") as file:
file_reader = csv.reader(file)
user_find(file_reader)
file.close()
def user_find(file):
user = input("Enter your username: ")
for row in file:
if row[0] == user:
print("username found", user)
user_found = [row[0],row[1]]
pass_check(user_found)
break
else:
print("not found")
def pass_check(user_found):
user = input("enter your password: ")
if user_found[1] == user:
print("password match")
else:
print("password not match")
main()

name in content checks whether name is anywhere in the string content. name may be any string whatsoever, so 'jo' in 'john,his_password' will happily find that 'jo' is indeed a substring of the content and evaluate to True.
You should actually parse the CSV:
existing_names = set() # in case the file is empty
with open("datafile.csv") as file:
existing_names = {
existing_name
for (existing_name, _) in csv.reader(file)
}
while True:
if name in existing_names:
name = input("name taken pls try again: ")
name = name.replace(" ", "")
else:
break

Related

Delete a line (name, contactnumber, emailaddress) by just searching for name in a phonebook

Good evening, I have a phonebook code but I am missing the delete feature. I cannot seem to make the delete feature work. All other features like insert, view, add contacts are working already.
I created a phnoebook txt file to store any entries.
phonebook = "d://phonebook.txt"
pbfile = open(phonebook, "a+")
pbfile.close
def show_main_menu():
''' Show main menu for Phone List '''
print("\n *** Phone List Menu ***\n"+
"------------------------------------------\n"+
"Enter 1, 2, 3 or 4:\n"+
"1: Display Your Contacts Records\n" +
"2: Add a New Contact Record\n"+
"3: Search your contacts\n"+
"4: Delete a Contact Record\n"+
"5: Quit\n**********************")
choice = input("Enter your choice: ")
if choice == "1":
pbfile = open(phonebook, "r+")
file_contents = pbfile.read()
if len(file_contents) == 0:
print("Phone List is empty")
else:
print (file_contents)
pbfile.close
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "2":
enter_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "3":
search_contact_record()
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
elif choice == "4":
delete_contact_record()
user_entry = ("Please Enter to Return to Main Menu ...")
show_main_menu()
elif choice== "5":
print("Thanks for using Phone List")
else:
print("Wrong choice, Please Enter [1 to 5]\n")
user_entry = input("Press Enter to Return to Main Menu ...")
show_main_menu()
I added the main menu above to show the menu of the phone book, there should be another choice to delete a contact.
The following code is to search for contact. It will show if a contact is already in the phone book but will mention not on record if there is no contact by the name they searched.
def search_contact_record():
''' This function is used to searches a specific contact record '''
contact_search = input("Enter First name to search for contact record: ")
contact_search = contact_search.title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_search in line:
print("You searched for:", end=" ")
print (line)
found=True
break
if found == False:
print("There's no contact Record in Phone List with name = " + contact_search )
The next function is to enter contact and add it to the phonebook txt file created in the beginning.
def enter_contact_record():
''' It collects contact info firstname, last name, email and phone '''
first = input('Enter First Name: ')
first = first.title()
last = input('Enter Last Name: ')
last = last.title()
phone = input('Enter Phone number: ')
email = input('Enter E-mail: ')
contact = ("[" + first + " " + last + ", " + phone + ", " + email + "]\n")
pbfile = open(phonebook, "a")
pbfile.write(contact)
print( "This contact\n " + contact + "has been added successfully!")
#def delete_contact():
show_main_menu()
I got confused on the part how to delete the contact from the txt phonebook. Last delete lines I have trying was the following
def delete_contact_record():
#Initiate a name variable
contact_delete = input('Enter the name of the contact you wish to delete: ').title()
pbfile = open(phonebook, "r+")
file_contents = pbfile.readlines()
found = False
for line in file_contents:
if contact_delete in line:
confirm = input('Are you sure you wish to delete '+contact_delete+' y/n?: ')
print(confirm)
if confirm == 'y':
del phonebook[contact_delete]
found = True
if found == False:
print('That contact does not exist! Return to the main menu to enter the contact')
it works up to the line asking for confirmation y/n. But when I enter Y, I get a TypeError: 'str' object does not support item deletion
Thank you.
Your main problem is that your phone book is a flat file. As such, a deletion is "rewrite the entire file, but without the deleted record."
This is, needless to say, very inefficient.
You will also have problems in the future with spurious matches for searches, since contact_search in line is perfectly happy to match parts of names.
Personally, I'd recommend using an SQLite3 database instead of a flat file (SQLite3 support is built in to Python). SQLite3 databases are actually single files, but you can use almost all of the SQL language to perform structured queries, and let it manage the file for you.
If writing SQL is too daunting, the SQLAlchemy Python package can help by making database tables work like Python classes.

I recently took interest in python using python3.8 and I' writing code to store user data and then verify it

I'm writing a code in python3.8 to ask user its Name, email, password and phone and storing then in different .txt file and now i have to verify it . Please help me write this program . I added a path in program. Now i need it to check if program has any pre-stored data like name,email,password and phone.And my working directory also have my program file. When I'm running it just getting to directly 2nd part where it's asking me for authentication. How should i define my program so that path does not include my program and checkpoints but only .txt files.
import os
path = 'C:\\Users\\User\\Downloads\\Class Work\\Project Python\\files'
dir = os.listdir(path)
# Here is the problem
if len(dir)==0:
with open ('name.txt','w') as Name:
Name.write(str(input("Name: ")))
with open('mobile.txt','w') as Mob:
Mob.write(str(input("Mobile No.: ")))
with open('email.txt','w') as email:
email.write(str(input("Email ID: ")))
with open('password.txt','w') as password:
password.write(input("password: "))
else: # Authentication
a= str(input("Enter email ID: "))
b=input("Enter Password: ")
with open('email.txt','r') as email:
x = email.read()
with open('password.txt','r') as password:
y= password.read()
if x==a and y==b:
with open('password.txt','w') as password:
password.write(input("New Password "))
else:
c = input("Enter Email ID: ")
d = input("Enter Phone: ")
with open('email.txt','r') as email:
s = email.read()
with open("mobile.txt",'r') as mobile:
t = mobile.read()
if c==s and d==t:
with open('password.txt','r') as password:
p = password.read()
print(p)
enter image description here
I guess you want just to see how python syntax works... I made a script similar to yours just with less stuff because extending it once you get how this works it's trivial.
#Here I declare a writing function:
#it accepts input from the user
#and save it into a file
def write(label,filename):
text = input(label)
f = open(filename,'w')
f.write(text)
f.close()
#This is a checking function:
#you insert name and password
#it reads the respective files
#if the input are the same of the
#stored one then the test it returns 1
#otherwise a 0
def check(filename1,filename2):
name = input('Insert your name: ')
pas = input('Insert your password: ')
f1 = open(filename1,'r')
f2 = open(filename2,'r')
stored_name = f1.read()
stored_pass = f2.read()
f1.close()
f2.close()
if stored_name == name and stored_pass == pas:
return 1
return 0
#Creating and saving the files
namefile = 'Name.dat'
passfile = 'Password.dat'
write('Insert your name: ',namefile)
write('Insert your password: ',passfile)
#Reading and checking
recovery = check(namefile,passfile)
if recovery == 1:
print ('everything correct')
else:
print ('wrong ID or pass')
Well i was able to create this program. I solved the problem by changing the dir(By importing 'os'. And used 'for' command to create a loop.
import os
# Setting dir and Changing it to access files from specific folder
path = 'C:\\Users\\user\\Downloads\\Class Work\\Project Python\\files'
os.chdir(path)
# checking if dir has any files
if len(os.listdir(path)) == 0 :
with open ('name.txt','w') as Name:
Name.write(str(input("Name: ")))
with open('mobile.txt','w') as Mob:
Mob.write(str(input("Mobile No.: ")))
with open('email.txt','w') as email:
email.write(str(input("Email ID: ")))
with open('password.txt','w') as password:
password.write(input("password: "))
else:
# Authentication
for i in range(3):
a= str(input("Enter Email ID: "))
b=input("Enter Password: ")
with open('email.txt','r') as email:
x = email.read()
with open('password.txt','r') as password:
y= password.read()
if x==a and y==b:
# If successful change password
with open('password.txt','w') as password:
password.write(input("New Password "))
break
else:
print("Try again")
else:
# IF not successful Show Password
# after verification of EMail ID and phone
c = str(input("Enter Email ID: "))
d = input("Enter Phone: ")
with open('email.txt','r') as email:
s = email.read()
with open("mobile.txt",'r') as mobile:
t = mobile.read()
if c==s and d==t:
with open('password.txt','r') as password:
p = password.read()
print(p)

python sava data into txt file

I have problem to create a full coding python file handling. I need all data functions in python will be save in txt file. Below is my coding.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = int(input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top
Management (e.g 1/2/3/4): "))
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
serLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%li "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
Actually, this program should have five requirements. First is staffRegistration(), staffLogin(), staffAttendance(), staffLeaveApplication(), approval() but I have done for two requirements only and I get stuck at staffLogin(). I need every function will be save in txt file (I mean the data in function).
In line 32 you try to convert a String into Integer. Besides, in your main function, you have an unresolved variable userLogin.
The other problem is in line 43 (staffLogin function), You want to write a long integer but you pass a string. I have tried to fix your code except for userLogin in main.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top Management (e.g 1/2/3/4): ")
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
userLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%s "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
There are a lot of problems in the staffLogin() function. e.g. the result of the first input()is bound to serLogin, but this should be userLogin.
If that is corrected, a password is read from the user, but nothing is ever done with it. Should the password be treated as an integer?
Also, if the user enters 2 at first prompt, the code will not set username but it will still try to write username to the file. That will raise a NameError exception.
Finally, the code attempts to write the characters in userLogin to the file as though they are integers. Not only will that not work, it doesn't make sense. Perhaps this should be writing the password to the file?

Read only lines and not the entire thing in python 2.7

How to I make it so in the code below when you register a username and password it it adds a new line to the txt files and when you login it checks every line in the txt files sepretly
and declaring it as correct if any of the lines match the login instead of it checking if the username and password matches the whole thing
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for
register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","w")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","w")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
if usr == file.read():
print "Username correct"
file.close()
else:
print "Username incorrect or not registered"
file.close()
file = open("Password.txt","r")
if pss == file.read():
print "Password correct"
file.close()
else:
print "Password incorrect or not registered"
file.close()
Here is how to find whether a string exists in some line of a file:
contain = False # Indicator of whether some line of a file contains the string
with open(FILENAME, 'r') as file: # Use `with` statement to automatically close file object
for line in file:
if string in line:
contain = True
break
I have modified your code to validate password and username with a password check logic. This should work.
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","a")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","a")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
file.close()
if not userfound:
raise
file = open("Password.txt","r")
passcount = 0
for passcode in file.readlines():
passcount += 1
if count == passcount:
if pss == passcode.strip():
print 'successfully logged in'
else:
print "Password incorrect or not registered"
break
file.close()
except Exception as e:
print 'User login error !!!'
If you just want to check if the user is in the file contents,
if usr in file.read():
do_somethin
"==" checks if the value are same as it is, "in" keyword checks if the substring is in the huge string. In file.read() will have the whole contents as a string.

(Python) How to test if a string is contained in a file

I'm trying to create a username database and the code all runs how I want except for when I try to test if the file contains the entered text. For some reason it just runs past the elif statement and hits the else statement if it already exists in the text.
Here is the full code:
class username:
def add():
while(True):
file = open("usernames.txt", 'r+')
names = list(file.read())
entered = str(input("Username: "))
if len(entered) == 0:
print("Please enter a valid username\n")
continue
elif not(entered.isalpha):
print("Please enter a valid username\n")
continue
elif entered in file.read():
print("That name is already in use.",
"\nPlease enter a different username. \n")
continue
elif len(entered) < 4 or len(entered) > 12:
print("Please enter a username with 4-12 characters.\n")
continue
else:
print(entered)
file.close()
add = open("usernames.txt", 'a+')
plusnewline = entered + "\n"
add.write(plusnewline)
add.close()
break
def list():
file = open("usernames.txt","r+")
names = file.read()
print(names)
file.close()
username.add()
username.list()
edit: Answered by Shadow:
Changed:
names = list(file.read())
to:
names = file.read()
and changed:
elif entered in file.read():
to:
elif entered in names:
You can only call file.read once - after that it's already read.
Either use file.seek(0) to go back to the start of the file (which will allow you to read it again), or cache the contents in a variable so that you can reuse it (that is, refer to your names variable)

Categories

Resources