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

半城伤御伤魂 提交于 2019-12-12 00:33:27

问题


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. "Yuvin Ng”, “Columbia College”, 778]
[2, “Ali”, “Douiglas 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.


回答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:

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?



来源:https://stackoverflow.com/questions/6638595/how-do-i-make-a-while-loop-so-it-reads-through-every-single-line-in-txt-file-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!