python使用CSV實現電話本

開始學習Python,看了一道程序 http://www.oschina.net/code/snippet_230735_8468, 在此基礎上修改了一下,

#!/bin/python
# coding:utf-8

import time
import csv

class 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 information

def 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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章