python使用CSV实现电话本

来源:互联网 发布:生产型进销存软件 编辑:程序博客网 时间:2024/05/29 15:59

开始学习Python,看了一道程序 http://www.oschina.net/code/snippet_230735_8468, 在此基础上修改了一下,

#!/bin/python# coding:utf-8import timeimport csvclass TelBook:    def __init__(self, filename):        self._filename = filename        """print title into file"""        csvfile = file(self._filename, "wb")        writer = csv.writer(csvfile)        title = ["NAME", "TEL", "TIME"]        writer.writerow(title)        csvfile.close()    def addPerson(self):        """Add a new person information"""        person = raw_input("Enter the person\'s name:")        tel = raw_input("Enter the person\'s tel:")        update = time.strftime("%Y-%m-%d %H:%m:%S")        writer = csv.writer(file(self._filename, "ab"))        writer.writerow([person, tel, update])    def findPerson(self, personname):        """find a person's information and print to terminal"""        csvfile = file(self._filename, "rb")        reader = csv.reader(csvfile)        flag = False        for person in reader:            if person[0] == personname:                print person                flag = True                break        if not flag:            print "Not find information of person with " + personname        csvfile.close()    #TODO:Delete person informationdef prompt():    print "a/A : add a person tel information;"    print "f/F : find a person tel information;"    print "q/Q : quit."def mainLoop():    obj = TelBook("telbook.csv")    flag = True    while flag:        choice = raw_input("Pls input your choice?(h for help)")        if choice == 'a' or choice == 'A':            obj.addPerson()        elif choice == 'f' or choice == 'F':            name = raw_input("Input the person\'s name you want to find:")            obj.findPerson(name)        elif choice == 'h' or choice == 'H':            prompt()        elif choice == 'q' or choice == 'Q':            print "Thank you! Bye-bye!"            flag = False        else:            print "Your input is invalid!"if __name__ == "__main__":    print "Welcome to TelBook!"    prompt()    mainLoop()

原创粉丝点击