python下pickle和file用法

一、pickle 用法

1、用户登录认证

-----------------------------create_user.py----------------------------
#!/usr/local/python
# -*- coding: utf-8 -*
import pickle

userInfo = {'git':['git','9000','9000'],
            'tom':['tom','8000','8000']
           }
pickle.dump(userInfo,open("userinfo","wb"))

-----------------------------cat_user.py-------------------------------
#!/usr/local/python
# -*- coding: utf-8 -*
import pickle

userinfo = open("userinfo","r")
while True:
    try:
        line = pickle.load(userinfo)
        print line
    except:
        break
-----------------------------user_auth.py------------------------------
#!/usr/local/python
# -*- coding: utf-8 -*
import pickle

userInfo = pickle.load(open("userinfo","rb"))
while True:
        accountAuth = raw_input("\033[;33mplease input user account:\033[0m").strip()
        if len(accountAuth) == 0:continue
        if userInfo.has_key(accountAuth):

                if 'lock' in userInfo[accountAuth]:   #判断用户是否被锁
                        print "%r user has been locked,please unlock" % accountAuth
                        exit()
                else:
                        for num in range(3,0,-1):
                                passwdAuth = raw_input("\033[;33mplease input user password:\033[0m").strip()
                                if len(passwdAuth) == 0:continue
                                if passwdAuth == userInfo[accountAuth][0]:
                                        print "hello,welcome to your home"
                                        exit()
                                else:
                                        print "wrong password,can try again %r itemes" % num

                        lockaccount = userInfo[accountAuth]
                        lockaccount.append("lock")
                        pickle.dump(userInfo,open("userinfo","wb"))
                        print "\033[;31mAccount freeze within 24 hours\033[0m"
                        exit()
        else:
                print "\033[;31mwrong account %r,please again"

2、生成和查看账单

------------------------------create_bill.py---------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*

import time,pickle

def Bill(Account,Time,Description,RMB):
    Bill = {"zhanghu":Account,"shijian":Time,"miaoshu":Description,"qianqian":RMB}
    #-----------------------------------------------------------------------------
    #此处引号中的zhanghu,shijian,miaoshu,qianqian是Bill字典中的key,而冒号后为value
    #-----------------------------------------------------------------------------
    pickle.dump(Bill,open("bill","a"))    

Bill(111,time.strftime("%Y-%m-%d %H:%M:%S"),"power","-200")
Bill(111,time.strftime("%Y-%m-%d %H:%M:%S"),"mouse","-300")

------------------------------query_bill.py----------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*

import pickle

print "Account\t\tTime\t\tDescription\t\tRMB"
f = open("bill","r")
while True:
    try:
        line = pickle.load(f)
        print "\033[;33m%r\t%r\t%r\t\t\t%r\033[0m" % (line["zhanghu"],line["shijian"],line["miaoshu"],line["qianqian"])
    except:
        break

脚本执行结果

[root@docker ~]# python query_bill.py 
Account                         Time    Description       RMB
    111         '2015-09-20 11:46:33'       'power'     '-200'
    111         '2015-09-20 11:46:33'       'mouse'     '-300'

二、readlines用法

readlines() 一次读取整个文件,自动将文件内容分析成一个行的列表,该列表可以由for … in … 进行处理

1、将文件已列表的形式导入到内存中

-----------------------------shops.txt---------------------------------
car      25000
iphone   4999
coffee   35
mac      9688
bicyle   432

-----------------------------shop_list.py------------------------------
#!/usr/bin/python
#coding=utf-8

products = []
prices = []

shops_file = file('shops.txt')
for line in shops_file.readlines():
        products.append(line.split()[0])    
        prices.append(int(line.split()[1]))

#-------------打印产品、价格菜单--------------
for p in products:
        p_index = products.index(p)
        p_price = prices[p_index]
        print p,'\t',p_price

脚本执行结果

[root@docker ~]# python shop.py 
car     25000
iphone  4999
coffee  35
mac     9688
bicyle  432

2、将文件已字典的形式导入到内存中

-----------------------------contact_list.txt--------------------------
1    zhangsan    IT     18212356434
2    lisi        HR     17482382344
3    wangwu      QA     12384722344
4    sunliu      JN     14234234235
5    tom         IT     23423343523

-----------------------------query_contact.py--------------------------
#!/usr/bin/python
#coding=utf-8
import tab
contact_dic = {}

contact_file='contact_list.txt'
f = file(contact_file)
for line in f.readlines():
    name = line.split()[1]  
    contact_dic[name] = line
#print contact_dic

for n,v in contact_dic.items():
    print n,'\t',v,

while True:
    input = raw_input("please input the staff name:").strip()
    if len(input) == 0:continue
    if contact_dic.has_key(input):
        print "\033[31;1m%s \033[0m" %contact_dic[input]
    else:
        print "sorry,no staff name found\n"

脚本执行结果

[root@docker ~]# python query_contact.py 
lisi     2    lisi        HR     17482382344
tom      5    tom         IT     23423343523
zhangsan 1    zhangsan    IT     18212356434
sunliu   4    sunliu      JN     14234234235
wangwu   3    wangwu      QA     12384722344
please input the staff name:tom
5    tom         IT     23423343523

please input the staff name:hero 
sorry,no staff name found

please input the staff name:

三、readline 用法

readline() 每次只读取文件中一行,一般与 if len(line) == 0:break 配合使用,来判断此文件是否读取完毕

-----------------------------contact_list.txt--------------------------
1    zhangsan    IT     18212356434
2    lisi        HR     17482382344
3    wangwu      QA     12384722344
4    sunliu      JN     14234234235
5    tom         IT     23423343523

-----------------------------query_contact.py--------------------------
#!/usr/bin/python
#coding=utf-8

while True:
        match_yes = 0
        input = raw_input("\033[32;1mmplease input the search name:\033[0m")
        contact_file = file('contact_list.txt')
        while True:
                line = contact_file.readline()
                if len(line) == 0:break
                if input in line:
                        print "match item:\033[36;1m%s\033[0m" %line
                        match_yes = 1
                #else:          
                #       print "no match item found"     
                #此处使用else会导致匹配后,还会继续打印出没匹配到的no match item found信息
        if match_yes == 0:
                print "no match item found"

脚本执行结果

[root@docker ~]# python shop.py 
mplease input the search name:zhangsan
match item:1    zhangsan    IT     18212356434

mplease input the search name:test
no match item found
mplease input the search name:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值