python下pickle和file用法

原创 2015年11月21日 16:34:39

一、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:
版权声明:本文为博主原创文章,未经博主允许不得转载。

python中序列化用法(pickle)

转自:http://www.pythonclub.org/modules/pickle python核心模块pickle和

Python持久化管理pickle模块 笔记

转自:http://blog.csdn.net/jq0123/article/details/4319589因为原来是中英对照的,为了自己复习起来方便,把英文都删了,还会加自己的理解Programmi...
  • Jurbo
  • Jurbo
  • 2016年08月14日 13:11
  • 3081

python核心模块之pickle和cPickle讲解

pickle模块使用的数据格式是python专用的,并且不同版本不向后兼容,同时也不能被其他语言说识别。要和其他语言交互,可以使用内置的json包使用pickle模块你可以把Python对象直接保存到...

python 之pickle模块--输出保存到文本(基本的数据序列和反序列化)

字典输出到文本该如何输出呢?遍历字典,输出也麻烦了,而且字典没有按顺序存储,读起来也麻烦。这个需求,导致的结果就是发现了这个好用的模块。 下面是一个字典的实例: #!/usr/bin/env ...

python序列化存储模块:Pickle

python序列化存储模块:Picklepython的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pic...

python笔记:pickle、cPickle模块

pickle包 1) 将内存中的对象转换成为文本流: import pickle # define class class Contact(object): def __...

python pickle

持久性就是指保持对象,甚至在多次执行同一程序之间也保持对象。通过本文,您会对 Python对象的各种持久性机制(从关系数据库到 Python 的 pickle以及其它机制)有一个总体认识。另外,还会让...

pickle ---python

pickle的序列化规则 http://blog.163.com/qiongling007@126/blog/static/214242962011110193074/ Python规范(Pyth...

python pickle模块

来源:http://www.cnblogs.com/cobbliu/archive/2012/09/04/2670178.html python pickle模块 ...
  • heybob
  • heybob
  • 2014年12月01日 16:01
  • 384

Python--序列化之pickle

pickle模块实现了二进制序列化和反序列化Python对象。
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:python下pickle和file用法
举报原因:
原因补充:

(最多只允许输入30个字)