V_Stack_2
V_Stack_2

Reputation: 157

How do i make a while loop so it reads through every single line in .txt file before it decide what to?

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.

Upvotes: 0

Views: 187

Answers (1)

Chris Gregg
Chris Gregg

Reputation: 2382

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?

Upvotes: 2

Related Questions