[py]python写一个通讯录step by step V3.0

python写一个通讯录step by step V3.0

参考: http://blog.51cto.com/lovelace/1631831

更新功能:

  • 数据库进行数据存入和读取操作
  • 字典配合函数调用实现switch功能
  • 其他:函数、字典、模块调用

注意问题:

  • 1、更优美的格式化输出
  • 2、把日期换算成年龄
  • 3、更新操作做的更优雅

准备工作
db准备

- 创建数据库

mysql> create database txl charset utf8;
Query OK, 1 row affected (0.09 sec)

mysql>

- 创建表
mysql> use txl;
Database changed

mysql> create table tb_txl (id int auto_increment primary key,name char(20),gender char(1),brithday date,tel char(20));
Query OK, 0 rows affected (0.29 sec)

mysql> desc tb_txl;
+----------+----------+------+-----+---------+----------------+
| Field    | Type     | Null | Key | Default | Extra          |
+----------+----------+------+-----+---------+----------------+
| id       | int(11)  | NO   | PRI | NULL    | auto_increment |
| name     | char(20) | YES  |     | NULL    |                |
| gender   | char(1)  | YES  |     | NULL    |                |
| brithday | date     | YES  |     | NULL    |                |
| tel      | char(20) | YES  |     | NULL    |                |
+----------+----------+------+-----+---------+----------------+

1、模板准备

相对于V1、V2、V3版本的,模板基本一致
模板

#!/usr/bin/env python
#coding:utf8
#Author:zhuima
#Date:2015-03-30
#Version:0.1
#Function:display a list and add date

# 导入模块
import os

def menu():
    '''设置munu目录,提供给用户的操作接口 '''
    print '''
        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program
    '''
    op = raw_input('Please select one >>> ')
    return op

def txl_exit():
    ''' 退出程序 '''
    os._exit(0)

def txl_error():
    ''' 当用户输出选项不在定义的选项内的时候,报错'''
    print
    print 'Unkonw options,Please try again!'

# 定义dict,配合函数实现switch功能

ops = {
#    '1':txl_add,
#    '2':txl_dis,
#    '3':txl_update,
#    '4':txl_del,
#    '5':txl_sort,
    '0':txl_exit,
}

def main():
    '''主程序 '''
    while True:
        op = menu()
        ops.get(op,txl_error)()

if __name__ == '__main__':
    main()

2、db_config准备

使用db配置单独生产一个配置文件,直接以模块的形式调用即可
db_config配置文件(调用数据库的好方法,值得借鉴)

[[email protected] day0330]# cat db_config.py
import MySQLdb

db_config = {
    'host' : 'localhost',
    'user' : 'root',
    'passwd' : 'zhuima',
    'charset' : 'utf8',
    'db': 'txl',
}

conn = MySQLdb.connect(**db_config)
cursor = conn.cursor()

3、连接数据库,实现增,查功能

导入db_config模块中的conn和cursor,然后直接使用
代码片段

确保自定义模块能够被正常导入

import sys
module_path = '/zhuima'
sys.path.append(module_path)

# 导入自定义模块
from db_config import conn,cursor

....

def txl_add():
    '''读取用户输入信息,并写入数据库'''
    name = raw_input('Please enput your name: ')
    gender = raw_input('Please enput your gender: ')
    brithday = raw_input('like (YYYY-MM-DD) >>> ')
    tel = raw_input('Please enput your tel: ')
    sql = 'insert into tb_txl  values (null,%s,%s,%s,%s)'
    cursor.execute(sql,(name,gender,brithday,tel))
    conn.commit()

def txl_dis():
    '''从数据库中提取信息,然后打印出来 '''
    sql = 'select name,gender,brithday,tel from tb_txl'
    cursor.execute(sql)
    info = cursor.fetchall()
    #print "%s\t%s\t%s\t%s" % info
    if len(info) > 0:
        print "name\tgender\tbrithday\ttel"
        print "---------------------------"
        #print info
        # 这里打印出来的结果未作处理
        for x in info:
            print x
    else:
        print
        print ">>> Empty,There is no user info in db <<<"
    #print  info

def txl_exit():
    '''关闭连接, 退出程序 '''
    cursor.close()
    conn.close()
    os._exit(0)

导入模块测试(如果db_config和当前脚本不在同一个目录下面,要设定path才行)

[[email protected] day0330]# python v3_1.py

    1.add user info
    2.disp all user info
    3.update user info by username
    4:del user by username
    5:sort user info by
    0.exit program

Please select one >>> 2
name    gender  brithday    tel
---------------------------
((u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086'),)

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 1
Please enput your name: nick
Please enput your gender: m
like (YYYY-MM-DD) >>> 1990-10-10
Please enput your tel: 10010

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 2
name    gender  brithday    tel
---------------------------
(u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086')
(u'nick', u'm', datetime.date(1990, 10, 10), u'10010')

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 0

4、连接数据库,实现删功能

导入db_config模块中的conn和cursor,然后直接使用
代码片段

def txl_del():
status = True
name = raw_input('Delete Information By Name >>> ')
select_sql = 'select name from tb_txl'
cursor.execute(select_sql)
info = cursor.fetchall()
print info
for line in info:
    if name in line:
        status = False
        delete_sql = 'delete from tb_txl where name=%s'
        cursor.execute(delete_sql,(name,))
        conn.commit()
if status:
    print
    print ">>>Unkonw User,Please Try again! <<<"

测试结果 (中间添加了print来调试代码)

[[email protected] day0330]# python v3_1.py

    1.add user info
    2.disp all user info
    3.update user info by username
    4:del user by username
    5:sort user info by
    0.exit program

Please select one >>> 2
name    gender  brithday    tel
------------------------------------
(u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086')
(u'kale', u'f', datetime.date(1988, 2, 18), u'10032')

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 4
Delete Information By Name >>> kale
((u'zhuima',), (u'kale',))

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 2
name    gender  brithday    tel
------------------------------------
(u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086')

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 4
Delete Information By Name >>> sdfsdf
((u'zhuima',),)

>>>Unkonw User,Please Try again! <<<

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:sort user info by
        0.exit program

Please select one >>> 0

5、连接数据库,实现更新功能

根据用户名搜索相关的值来进行更新
update实例演示

mysql> select * from tb_txl;
+----+--------+--------+------------+-------+
| id | name   | gender | brithday   | tel   |
+----+--------+--------+------------+-------+
|  1 | zhuima | f      | 1988-12-08 | 10086 |
|  6 | nick   | m      | 1990-10-06 | 10011 |
+----+--------+--------+------------+-------+
2 rows in set (0.00 sec)

mysql> update tb_txl set tel='10010' where name='nick';
Query OK, 1 row affected (0.22 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tb_txl;
+----+--------+--------+------------+-------+
| id | name   | gender | brithday   | tel   |
+----+--------+--------+------------+-------+
|  1 | zhuima | f      | 1988-12-08 | 10086 |
|  6 | nick   | m      | 1990-10-06 | 10010 |
+----+--------+--------+------------+-------+
2 rows in set (0.00 sec)

mysql>
代码片段
def txl_update():
statue = True
name = raw_input('Update Information By Name >>> ')
select_sql = 'select name from tb_txl'
cursor.execute(select_sql)
info = cursor.fetchall()
for line in info:
    if name in line:
        status = False
        gender = raw_input('Update Your Gender for %s >>> ' % name)
        brithday = raw_input('Update Your Brithday like (YYYY-MM-DD) for %s >>> ' % name)
        tel = raw_input('Update Your Tel for %s >>> '% name)

        update_sql = 'update tb_txl set gender=%s,brithday=%s,tel=%s where name=%s'
        cursor.execute(update_sql,(gender,brithday,tel,name,))
        conn.commit()

if status:
    print
    print ">>>Unkonw User,Please Try again! <<<"
执行结果
[[email protected] day0330]# python v3_1.py

    1.add user info
    2.disp all user info
    3.update user info by username
    4:del user by username
    5:check user info by username
    0.exit program

Please select one >>> 2
name    gender  brithday    tel
------------------------------------
(u'nick', u'm', datetime.date(1990, 10, 6), u'10010')
(u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086')

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:check user info by username
        0.exit program

Please select one >>> 3
Update Information By Name >>> zhuima
Update Your Gender for zhuima >>> m
Update Your Brithday like (YYYY-MM-DD) for zhuima >>> 1990-10-10
Update Your Tel for zhuima >>> 10000

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:check user info by username
        0.exit program

Please select one >>> 2
name    gender  brithday    tel
------------------------------------
(u'nick', u'm', datetime.date(1990, 10, 6), u'10010')
(u'zhuima', u'm', datetime.date(1990, 10, 10), u'10000')

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:check user info by username
        0.exit program

Please select one >>> 5
Enter The name >>> sdfsdf

>>>Unkonw User,Please Try again! <<<

6、连接数据库,实现检索功能

根据用户名搜索相关的值然后返显结果
代码片段

def txl_check():
status = True
name = raw_input('Enter The name >>> ')
cursor.execute('select * from tb_txl')
info = cursor.fetchall()
for line in info:
    if name in line:
        status = False
        print line

if status:
    print
    print ">>>Unkonw User,Please Try again! <<<"
测试结果
[[email protected] day0330]# python v3_1.py

1.add user info
2.disp all user info
3.update user info by username
4:del user by username
5:check user info by username
0.exit program

Please select one >>> 5
Enter The name >>> sdfs

>>>Unkonw User,Please Try again! <<<

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:check user info by username
        0.exit program

Please select one >>> 5
Enter The name >>> nick
(6L, u'nick', u'm', datetime.date(1990, 10, 6), u'10010')

        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:check user info by username
        0.exit program

Please select one >>>

完整代码

    #!/usr/bin/env python
    #coding:utf8
    #Author:zhuima
    #Date:2015-03-22
    #Version:0.1
    #Function:display a list and add date

    # 导入模块
    import os

    #确保自定义模块能够被正常导入
    import sys
    module_path = '/zhuima'
    sys.path.append(module_path)

    # 导入自定义模块
    from db_config import conn,cursor

    def menu():
        '''设置munu目录,提供给用户的操作接口 '''
        print '''
            1.add user info
            2.disp all user info
            3.update user info by username
            4:del user by username
            5:check user info by username
            0.exit program
        '''
        op = raw_input('Please select one >>> ')
        return op

    def txl_add():
        '''读取用户输入信息,并写入数据库'''
        name = raw_input('Please enput your name: ')
        gender = raw_input('Please enput your gender: ')
        brithday = raw_input('like (YYYY-MM-DD) >>> ')
        tel = raw_input('Please enput your tel: ')
        sql = 'insert into tb_txl  values (null,%s,%s,%s,%s)'
        cursor.execute(sql,(name,gender,brithday,tel))
        conn.commit()

    def txl_dis():
        '''从数据库中提取信息,然后打印出来 '''
        sql = 'select name,gender,brithday,tel from tb_txl'
        cursor.execute(sql)
        info = cursor.fetchall()
        #print "%s\t%s\t%s\t%s" % info
        if len(info) > 0:
            print "name\tgender\tbrithday\ttel"
            print "------------------------------------"
            #print info
            for x in info:
                print x
        else:
            print
            print ">>> Empty,There is no user info in db <<<"
        #print  info

    def txl_del():
        status = True
        name = raw_input('Delete Information By Name >>> ')
        select_sql = 'select name from tb_txl'
        cursor.execute(select_sql)
        info = cursor.fetchall()
        for line in info:
            if name in line:
                status = False
                delete_sql = 'delete from tb_txl where name=%s'
                cursor.execute(delete_sql,(name,))
                conn.commit()
        if status:
            print
            print ">>>Unkonw User,Please Try again! <<<"

    def txl_update():
        statue = True
        name = raw_input('Update Information By Name >>> ')
        select_sql = 'select name from tb_txl'
        cursor.execute(select_sql)
        info = cursor.fetchall()
        for line in info:
            if name in line:
                status = False
                gender = raw_input('Update Your Gender for %s >>> ' % name)
                brithday = raw_input('Update Your Brithday like (YYYY-MM-DD) for %s >>> ' % name)
                tel = raw_input('Update Your Tel for %s >>> '% name)

                update_sql = 'update tb_txl set gender=%s,brithday=%s,tel=%s where name=%s'
                cursor.execute(update_sql,(gender,brithday,tel,name,))
                conn.commit()

        if status:
            print
            print ">>>Unkonw User,Please Try again! <<<"

    def txl_check():
        status = True
        name = raw_input('Enter The name >>> ')
        cursor.execute('select * from tb_txl')
        info = cursor.fetchall()
        for line in info:
            if name in line:
                status = False
                print line

        if status:
            print
            print ">>>Unkonw User,Please Try again! <<<"

    def txl_exit():
        ''' 退出程序 '''
        cursor.close()
        conn.close()
        os._exit(0)

    def txl_error():
        ''' 当用户输出选项不在定义的选项内的时候,报错'''
        print
        print 'Unkonw options,Please try again!'

    # 定义dict,配合函数实现switch功能

    ops = {
        '1':txl_add,
        '2':txl_dis,
        '3':txl_update,
        '4':txl_del,
        '5':txl_check,
        '0':txl_exit,
    }

    def main():
        '''主程序 '''
        while True:
            op = menu()
            ops.get(op,txl_error)()

    if __name__ == '__main__':
        main()

实现格式化输出

brithday输出更正为输出为具体年龄,可视化更强
引入datetime模块
代码片段

def txl_dis():
'''从数据库中提取信息,然后打印出来 '''
status = True
sql = 'select name,gender,brithday,tel from tb_txl'
cursor.execute(sql)
info = cursor.fetchall()
if len(info) > 0:
    status = False
    print "name\tgender\tbrithday\ttel"
    print "------------------------------------"
    for name,gender,age,tel in info:
        today = datetime.date.today()
        age = (today-age).days/365
        print "%(name)s\t%(gender)s\t%(age)s\t\t%(tel)s" % locals()

if status:
    print
    print ">>> Empty,There is no user info in db <<<"

格式化之后的初始版本的脚本:

#!/usr/bin/env python
#coding:utf8
#Author:zhuima
#Date:2015-03-22
#Version:0.1
#Function:display a list and add date

# 导入模块
import os
import datetime

#确保自定义模块能够被正常导入
import sys
module_path = '/zhuima'
sys.path.append(module_path)

# 导入自定义模块
from db_config import conn,cursor

def menu():
    '''设置munu目录,提供给用户的操作接口 '''
    print '''
        1.add user info
        2.disp all user info
        3.update user info by username
        4:del user by username
        5:check user info by username
        0.exit program
    '''
    op = raw_input('Please select one >>> ')
    return op

def txl_add():
    '''读取用户输入信息,并写入数据库'''
    name = raw_input('Please enput your name: ')
    gender = raw_input('Please enput your gender: ')
    brithday = raw_input('like (YYYY-MM-DD) >>> ')
    tel = raw_input('Please enput your tel: ')
    sql = 'insert into tb_txl  values (null,%s,%s,%s,%s)'
    cursor.execute(sql,(name,gender,brithday,tel))
    conn.commit()

def txl_dis(name=None):
    '''从数据库中提取信息,然后打印出来 '''
    status = True
    sql = 'select name,gender,brithday,tel from tb_txl'
    cursor.execute(sql)
    info = cursor.fetchall()

    if len(info) > 0:
        status = False
        print "name\tgender\tage\ttel"
        print "------------------------------------"
        for name,gender,age,tel in info:
            today = datetime.date.today()
            age = (today-age).days/365
            print "%(name)s\t%(gender)s\t%(age)s\t%(tel)s" % locals()

    if status:
        print
        print ">>> Empty,There is no user info in db <<<"
    #print  info

def txl_del():
    status = True
    name = raw_input('Delete Information By Name >>> ')
    select_sql = 'select name from tb_txl'
    cursor.execute(select_sql)
    info = cursor.fetchall()
    for line in info:
        if name in line:
            status = False
            delete_sql = 'delete from tb_txl where name=%s'
            cursor.execute(delete_sql,(name,))
            conn.commit()
    if status:
        print
        print ">>>Unkonw User,Please Try again! <<<"

def txl_update():
    statue = True
    name = raw_input('Update Information By Name >>> ')
    select_sql = 'select name from tb_txl'
    cursor.execute(select_sql)
    info = cursor.fetchall()
    for line in info:
        if name in line:
            status = False
            gender = raw_input('Update Your Gender for %s >>> ' % name)
            brithday = raw_input('Update Your Brithday like (YYYY-MM-DD) for %s >>> ' % name)
            tel = raw_input('Update Your Tel for %s >>> '% name)

            update_sql = 'update tb_txl set gender=%s,brithday=%s,tel=%s where name=%s'
            cursor.execute(update_sql,(gender,brithday,tel,name,))
            conn.commit()

    if status:
        print
        print ">>>Unkonw User,Please Try again! <<<"

def txl_check():
    status = True
    name = raw_input('Enter The name >>> ')
    sql = 'select name,gender,brithday,tel from tb_txl where name = %s'
    cursor.execute(sql,(name,))
    info = cursor.fetchall()
    if len(info) > 0:
        status = False
        print "name\tgender\tbrithday\ttel"
        print "------------------------------------"
        for name,gender,age,tel in info:
            today = datetime.date.today()
            age = (today-age).days/365
            print "%(name)s\t%(gender)s\t%(age)s\t%(tel)s" % locals()
    if status:
        print
        print ">>> Empty,There is no user info in db <<<"

def txl_exit():
    ''' 退出程序 '''
    cursor.close()
    conn.close()
    os._exit(0)

def txl_error():
    ''' 当用户输出选项不在定义的选项内的时候,报错'''
    print
    print 'Unkonw options,Please try again!'

def main():
    '''主程序 '''
    # 定义dict,配合函数实现switch功能

    ops = {
        '1':txl_add,
        '2':txl_dis,
        '3':txl_update,
        '4':txl_del,
        '5':txl_check,
        '0':txl_exit,
    }
    while True:
        op = menu()
        ops.get(op,txl_error)()

if __name__ == '__main__':
    main()

脚本中存在着很多重复代码以及bug,仅作参考,如果哪位想要调试可以进行下载重新更改

v1.0 v2.0版本

python写一个通讯录step by step V1.0
python写一个通讯录step by step V2.0

原文地址:https://www.cnblogs.com/iiiiiher/p/8215040.html

时间: 2024-08-04 05:51:03

[py]python写一个通讯录step by step V3.0的相关文章

python写一个通讯录V2.0

python写一个通讯录step by step V2.0 引用知识 list + dict用于临时存储用户数据信息 cPickle用于格式化文件存取 依旧使用file来进行文件的存储 解决问题 1.操刀开始去做 原始代码 实现功能(可做模板) 1.判断输入内容是否在给出的menu目录内,在的话,返回对应结果,不在就报错 2.调用os模块的exit功能 3.字典配合循环加上函数实现switch的功能 #!/usr/bin/env python #coding:utf8 #Author:zhuim

python写一个通讯录

闲着没事,用python写一个模拟通讯录,要求要实现常用的通讯录的功能,基本流程如下 ? 接下来就按照这个流程实现各个模块的功能 1. 定义一个类,并初始化 1 import json 2 import time 3 4 5 class Address(object): 6 def __init__(self): 7 with open("通讯录.txt", 'r', encoding='utf-8') as f: 8 self.data = json.loads(f.read())

用Python写一个ftp下载脚本

用Python写一个ftp下载脚本 ----基于Red Hat Enterprise Linux Server release 6.4 (Santiago):python 2.6.6 Ps:少侠我接触Python半个月以来接到的第一个需求,虽然如此简单的一个脚本,少侠我磕磕绊绊却用了将近一天半的时间才写出来,但还是很开心,毕竟也粗来了,废话不多说,切入正题.因为一开始没有用过ftplib模块,所以各种谷歌度娘一堆资料杂乱不堪,话不清,理不乱的,本文实现的功能简单,下面介绍一下,以免误导读者. 需

老男孩教育每日一题-2017-04-17:使用Shell或Python写一个脚本,CPU使用率超过80%或硬盘超过85%邮件报警

老男孩教育每日一题-2017-04-17: 使用Shell或Python写一个脚本,CPU使用率超过80%或硬盘超过85%邮件报警. 今天是老男孩教育每日一题陪伴大家的第29天.

python写一个脚本解析文件

Python写一个脚本解析文件 ----基于Red Hat Enterprise Linux Server release 6.4 (Santiago):python 2.6.6 需求: 1.去掉空行 2.去掉空行后输出到一个新文件 附加需求(排版):1.'-'缩进n个字符 '-'缩进2n个字符 以此类推 2.'-'开头的所有句子输出在一行 '-'开头的句子输出在一行 以此类推 --------------------------------------------分隔线------------

十行代码--用python写一个USB病毒 (知乎 DeepWeaver)

昨天在上厕所的时候突发奇想,当你把usb插进去的时候,能不能自动执行usb上的程序.查了一下,发现只有windows上可以,具体的大家也可以搜索(搜索关键词usb autorun)到.但是,如果我想,比如,当一个usb插入时,在后台自动把usb里的重要文件神不知鬼不觉地拷贝到本地或者上传到某个服务器,就需要特殊的软件辅助. 于是我心想,能不能用python写一个程序,让它在后台运行.每当有u盘插入的时候,就自动拷贝其中重要文件. 如何判断U盘的插入与否? 首先我们打开电脑终端,进入/Volume

写一个脚本,实现判断10.0.0.0/24网络里,当前在线用户的IP有哪些

#!/bin/bash #检测一个c的ip中当前有哪些IP在线 for i in `seq 1 254`;do #{} 开启并发,开启多线程 { IP=10.0.0.$i ping -c1 -w 1 $IP >/dev/null #判断ip是否在线,把在线的ip输出到指定文本并显示到屏幕 if [ $? -eq 0 ];then echo "Host $IP is ok" echo $IP >>/tmp/ip.txt fi # &把命令放入后台 } &

基于zabbix用Python写一个运维流量气象图

前言:同事问我,你写运维平台最先写哪一部分?好吧,还真把我问倒了,因为这是在问最应该放在放在第一位的东西~作为一个工作不足两年,运维不足一年的新手来说,还真不敢妄下评论,其实按照我的思路,觉得最重要的部分肯定是故障处理,报警,但是这一块怎么写?怎么说?肯定不能重复造轮子了,不过我最想写的是报表系统,思路是有的,但是一直耽搁了,详情参考http://youerning.blog.51cto.com/10513771/1708925. 好吧,在回到那个问题,应该先写哪个部分.我没回答,反问他了. 他

Hello Python!用python写一个抓取CSDN博客文章的简单爬虫

网络上一提到python,总会有一些不知道是黑还是粉的人大喊着:python是世界上最好的语言.最近利用业余时间体验了下python语言,并写了个爬虫爬取我csdn上关注的几个大神的博客,然后利用leancloud一站式后端云服务器存储数据,再写了一个android app展示数据,也算小试了一下这门语言,给我的感觉就是,像python这类弱类型的动态语言相比于java来说,开发者不需要分太多心去考虑编程问题,能够把精力集中于业务上,思考逻辑的实现.下面分享一下我此次写爬虫的一下小经验,抛砖引玉