Skip to content Skip to sidebar Skip to footer

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 custome

Solution 1:

First of all, you don't need the two while statements. Also, you need to close the file before you return. Something like this:

defaddingcustomer(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:

defaddingcustomer(file_name,new_name):
    f=open(file_name,"r+")
    for line in f:
        if new_name in line:
            f.close()
            returnFalse# the name didn't exist
    f.write(new_name)
    f.write("\n")
    f.close()
    returnTrue

A bigger question is, what format is new_name in to begin with?

Post a Comment for "How Do I Make A While Loop So It Reads Through Every Single Line In .txt File Before It Decide What To?"