백엔드 개발 파이썬 튜토리얼 python使用marshal模块序列化实例

python使用marshal模块序列化实例

Jun 16, 2016 am 08:41 AM
marshal python 직렬화 기준 치수

本文实例讲述了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版本之间的兼容性,所以保留个版本信息的函数.

希望本文所述对大家Python程序设计的学习有所帮助。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Apr 01, 2025 pm 05:09 PM

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? Apr 01, 2025 pm 04:03 PM

SCAPY 크롤러를 사용할 때 파이프 라인 영구 스토리지 파일을 작성할 수없는 이유는 무엇입니까? 토론 Data Crawler에 Scapy Crawler를 사용하는 법을 배울 때 종종 ...

파이썬 모래시 그래프 그리기 : 가변적 인 정의되지 않은 오류를 피하는 방법? 파이썬 모래시 그래프 그리기 : 가변적 인 정의되지 않은 오류를 피하는 방법? Apr 01, 2025 pm 06:27 PM

Python : 모래 시계 그래픽 도면 및 입력 검증을 시작 하기이 기사는 모래 시계 그래픽 드로잉 프로그램에서 Python 초보자가 발생하는 변수 정의 문제를 해결합니다. 암호...

Python Process Pool이 동시 TCP 요청을 처리하고 클라이언트가 막히게하는 이유는 무엇입니까? Python Process Pool이 동시 TCP 요청을 처리하고 클라이언트가 막히게하는 이유는 무엇입니까? Apr 01, 2025 pm 04:09 PM

Python Process Pool은 클라이언트가 갇히게하는 동시 TCP 요청을 처리합니다. 네트워크 프로그래밍에 Python을 사용하는 경우 동시 TCP 요청을 효율적으로 처리하는 것이 중요합니다. ...

Python functools.partial 객체가 내부적으로 캡슐화 한 원래 함수를 보는 방법? Python functools.partial 객체가 내부적으로 캡슐화 한 원래 함수를 보는 방법? Apr 01, 2025 pm 04:15 PM

functools.partial in Python의 파이썬 funcTools.partial 객체의 시청 방법을 깊이 탐구하십시오 ...

Python Cross-Platform 데스크탑 응용 프로그램 개발 : 어떤 GUI 라이브러리가 가장 적합합니까? Python Cross-Platform 데스크탑 응용 프로그램 개발 : 어떤 GUI 라이브러리가 가장 적합합니까? Apr 01, 2025 pm 05:24 PM

Python 크로스 플랫폼 데스크톱 응용 프로그램 개발 라이브러리 선택 많은 Python 개발자가 Windows 및 Linux 시스템 모두에서 실행할 수있는 데스크탑 응용 프로그램을 개발하고자합니다 ...

한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? 한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? Apr 01, 2025 pm 11:15 PM

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Google과 AWS는 공개 PYPI 이미지 소스를 제공합니까? Google과 AWS는 공개 PYPI 이미지 소스를 제공합니까? Apr 01, 2025 pm 05:15 PM

많은 개발자들이 PYPI (PythonPackageIndex)에 의존합니다 ...

See all articles