Name
load, loads
Synopsis
load(fileobj
) loads(str
)
loads
creates and returns the object
v
previously dumped to string
str
, so that, for any object
v
of a supported type,
v
equals
loads(dumps(
v
))
.
If str
is longer than
dumps(
v
)
,
loads
ignores the extra bytes.
load
reads the right number of bytes from file
object fileobj
, which must be opened for
reading in binary mode, and creates and returns the object
v
represented by those bytes.
fileobj
cannot be a file-like object: it
must be an instance of type file
.
Functions load
and dump
are
complementary. In other words, a sequence of calls to
load(
f
)
deserializes the same values previously serialized when
f
’s contents were created
by a sequence of calls to
dump(
v
,f
)
.
Objects that are dumped and loaded in this way can be instances of
any mix of supported types.
Suppose you need to analyze several text files, whose names are given
as your program’s arguments, and record where each
word appears in those files. The data you need to record for each
word is a list of
(
filename
,
line-number
)
pairs. The
following example uses marshal
to encode lists of
(
filename
,
line-number
)
pairs as
strings and store them in a DBM-like file (as covered later in this
chapter). Since those lists contain tuples, each made up of a string
and a number, they are within
marshal
’s abilities to serialize.
import fileinput, marshal, anydbm wordPos = { } for line in fileinput.input( ): pos = fileinput.filename( ), fileinput.filelineno( ) for word in line.split( ...
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.