Im creating a function called addingcustomer(n): so i need it to read through every single line in the .txt to make sure there is no repeated customer name only add the new customer name: my customer.txt:
[1. "Aden A”, “C College”, 778]
[2, “Ali”, “D College”, 77238]
my current function:
def addingcustomer(file_name,new_name):
f=open(file_name,"r+")
for line in f:
while new_name in line:
return ("The Customer existed")
while new_name not in line:
f=open("file_name","w")
f.write(list(new_name)+"\n")
f.close()
how can i create a while loop to make it function as a addition of a list to the current.txt file. im so sorry i tried my best and im stuck.
First of all, you don't need the two while
statements. Also, you need to close the file before you return. Something like this:
def addingcustomer(file_name,new_name):
f=open(file_name,"r+")
for line in f:
if new_name in line:
f.close()
return ("The Customer existed")
# the name didn't exist
f.write(str(list(new_name)+"\n")
f.close()
return ("Added new customer.")
If I were doing it, however, I'd return either True
or False
to indicate that a customer had been added:
def addingcustomer(file_name,new_name):
f=open(file_name,"r+")
for line in f:
if new_name in line:
f.close()
return False
# the name didn't exist
f.write(new_name)
f.write("\n")
f.close()
return True
A bigger question is, what format is new_name
in to begin with?