发布于 2014-09-30 01:40:02 | 170 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python教程,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


本文主要为大家讲解的是python下使用marshal模块序列化的方法,感兴趣的同学参考下.

python使用marshal模块序列化实例如下:

先来看看下面这段代码:

import marshal
data1 = ['abc',12,23,'jb51']  #几个测试数据
data2 = {1:'aaa',"b":'dad'}
data3 = (1,2,4)

output_file = open("a.txt",'wb')#把这些数据序列化到文件中,注:文件必须以二进制模式打开
marshal.dump(data1,output_file)
marshal.dump(data2,output_file)
marshal.dump(data3,output_file)
output_file.close()


input_file = open('a.txt','rb')#从文件中读取序列化的数据
#data1 = []
data1 = marshal.load(input_file)
data2 = marshal.load(input_file)
data3 = marshal.load(input_file)
print data1#给同志们打印出结果看看
print data2
print data3


outstring = marshal.dumps(data1)#marshal.dumps()返回是一个字节串,该字节串用于写入文件
open('out.txt','wb').write(outstring)

file_data = open('out.txt','rb').read()
real_data = marshal.loads(file_data)
print real_data

结果:

['abc', 12, 23, 'jb51']
{1: 'aaa', 'b': 'dad'}
(1, 2, 4)
['abc', 12, 23, 'jb51']

marshel模块的几个函数官方描述如下:

The module defines these functions:
marshal.dump(value, file[, version])
Write the value on the open file. The value must be a supported type. The file must be an open file object such as sys.stdout or returned by open() or os.popen(). It must be opened in binary mode ('wb' or 'w+b').
If the value has (or contains an object that has) an unsupported type, a ValueError exception is raised — but garbage data will also be written to the file. The object will not be properly read back by load().
New in version 2.4: The version argument indicates the data format that dump should use (see below).
marshal.load(file)
Read one value from the open file and return it. If no valid value is read (e.g. because the data has a different Python version's incompatible marshal format), raise EOFError, ValueError or TypeError. The file must be an open file object opened in binary mode ('rb' or 'r+b').
Warning
If an object containing an unsupported type was marshalled with dump(), load() will substitute None for the unmarshallable type.
marshal.dumps(value[, version])
Return the string that would be written to a file by dump(value, file). The value must be a supported type. Raise a ValueError exception if value has (or contains an object that has) an unsupported type.
New in version 2.4: The version argument indicates the data format that dumps should use (see below).
marshal.loads(string)
Convert the string to a value. If no valid value is found, raise EOFError, ValueError or TypeError. Extra characters in the string are ignored.
In addition, the following constants are defined:
marshal.version
Indicates the format that the module uses.

marshal.version的用处marshal不保证不同的python版本之间的兼容性,所以保留个版本信息的函数.

 



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务